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

function Unlock-KeyChain {
    [CmdletBinding()]
    param (
        [securestring] $Password
    )

    if ($Password) {
        & $securityCmd unlock-keychain -p ($Password | ConvertFrom-SecureString -AsPlainText) $keyChainName
    }
    else {
        & $securityCmd unlock-keychain $keyChainName
    }
}

function Set-KeyChainConfiguration {
    [CmdletBinding()]
    param (
        [SecureString] $Password,
        [int] $PasswordTimeout
    )

    if ($PasswordTimeout -eq 0) {
        & $securityCmd set-keychain-settings $keyChainName
    }
    else {
        & $securityCmd set-keychain-settings -t $PasswordTimeout $keyChainName
    }

    if ($Password) {
        & $securityCmd set-keychain-password -p ($Password | ConvertFrom-SecureString -AsPlainText) $keyChainName
    }
}

function Get-KeyChainConfiguration {
    [CmdletBinding()]
    param ()

    $null = Test-SecretVault -VaultName $keyChainName
    $out = & $securityCmd show-keychain-info $keyChainName 2>&1

    # example output:
    # Keychain "SecretManagement.KeyChain" lock-on-sleep timeout=300s
    if ($out -match 'timeout=(.*?)s') {
        $timeout = $matches[1]
    }
    elseif ($out -match 'no-timeout') {
        $timeout = 0
    }
    else {
        throw "Could not parse KeyChain configuration info"
    }

    [PSCustomObject]@{
        Name = $keyChainName
        PasswordTimeout = $timeout
    }
}