TUN.Credentials.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
###
# Name: TUN.Credentials
# Author: Markus Szumovski
# Creation Date: 2020-06-18
# Purpose/Change: Methods to easily manage and use credentials
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/
###

Set-StrictMode -Version Latest

[hashtable] $script:CachedCredentials = @{}                     # Cached credentials by name

function Get-CredentialInternal {
    <#
        .SYNOPSIS
            Retrieves credentials from user
        .PARAMETER Message
            Message to prompt for credential input.
            Default is "Please enter credentials"
        .PARAMETER Usage
            Optional string describing the usage for the credentials (will be appended to "Initializing credentials for <$Usage>").
        .PARAMETER NoOutput
            True/Present...Will not display any messages to the host
        .OUTPUTS
            Retrieved PSCredential object or null
    #>

    
    [CmdletBinding()]
    PARAM (
        [Parameter(Position=0)]
        [string] $Message,
        [Parameter(Position=1)]
        [string] $Usage,
        [Parameter(Position=2)]
        [switch] $NoOutput
    )
    
    if(!$NoOutput.IsPresent) {
        if($Usage) {
            Write-Host "Initializing credentials for $Usage..."
        }
        else {
            Write-Host "Initializing credentials..."
        }
    }
    $Credential = Get-Credential -Message $Message

    if(!$NoOutput.IsPresent) {
        if(!$Credential) {
            if($Usage) {
                Write-Host "Credentials input canceled for $Usage"
            }
            else {
                Write-Host "Credentials input canceled"
            }
        }
    }

    return $Credential
}

function Use-PSCredential {
    <#
        .SYNOPSIS
            Gets PS credentials from a cache, file or user input (in that order) and save it to a file and cache.
            If file and/or cache will be used to store the credentials can be configured.
        .PARAMETER Name
            Unique cache name for the credentials.
            If no cache name is provided, the credentials will not be cached.
        .PARAMETER File
            File to store credentials in and read credentials from.
            Information will be stored in the XML file format.
            If no path for a credentials file was provided this method will not save the credentials to a file.
        .PARAMETER Message
            Message to prompt for credential input.
            Default is "Please enter credentials"
        .PARAMETER Usage
            Optional string describing the usage for the credentials (will be appended to "Initializing credentials for <$Usage>").
            This will be ignored if the -NoOuptut switch was provided.
        .PARAMETER ErrorOnNone
            True/Present...Will throw an error if no credentials were found (even though File or Name was given in case of NoUnstored switch present)
        .PARAMETER NoInput
            True/Present...Will expect a name or file path to be provided and for there to already be a stored credential (exception: Init switch)
        .PARAMETER NoUnstored
            True/Present...Will not ask for credentials if no file path or cache name was provided
        .PARAMETER Init
            True/Present...If the File parameter was provided:
                            The script will ask for the credentials to use, store them in a credentials file and will then immediatly exit the script.
                            Used to either set up credentials file for the first time, or change/renew the credentials in the credential file, without performing the
                            actual task by the script. The -WhatIf switch cannot be used to make sure the script is not performing its task, because it will also prevent
                            the script from saving the credentials to the credentials file.
                            This switch is ignored if the CredentialsFile parameter is not provided.
                            If the Name parameter was provided:
                            Will clear the cache of these credentials and ask for a user input of credentials.
        .PARAMETER NoOutput
            True/Present...Will not display any messages to the host (except if canceling execution due to Init switch being present)
        .OUTPUTS
            Retrieved PSCredential object or null
    #>


    [CmdletBinding()]
    PARAM (
        [Parameter(Position=0)]
        [string] $Name = $null,
        [Parameter(Position=1)]
        [string] $File = $null,
        [Parameter(Position=2)]
        [string] $Message = "Please enter credentials",
        [Parameter(Position=3)]
        [string] $Usage = $null,
        [Parameter(Position=4)]
        [switch] $ErrorOnNone,
        [Parameter(Position=5)]
        [switch] $NoInput,
        [Parameter(Position=6)]
        [switch] $NoUnstored,
        [Parameter(Position=7)]
        [switch] $Init,
        [Parameter(Position=8)]
        [switch] $NoOutput
    )

    [bool] $ShowedCredentialDialog = $false
    [PSCredential] $Credential = $null

    if($Name -and $script:CachedCredentials.ContainsKey($Name)) {
        If($Init.IsPresent) {
            Clear-CredentialCache -Name $Name -NoOutput:$NoOutput
        }
        else {
            $Credential = $script:CachedCredentials[$Name]
        }
    }

    #check for credential file
    if($File) {
        If($Init.IsPresent -or !(Test-Path $File)) {
            if(!$ShowedCredentialDialog -and !$Credential) {
                if(!$NoInput.IsPresent -or $Init.IsPresent) {
                    $Credential = Get-CredentialInternal -Message $Message -Usage $Usage -NoOutput:$NoOutput
                }
                $ShowedCredentialDialog = $true
            }

            if($Credential) {
                if(!$NoOutput.IsPresent) {
                    Write-Host "Saving credentials to file..."
                }
                $Credential | Export-Clixml -Path $File
            }   

            if($Init.IsPresent) {
                Write-Host "Ending script since the 'initialize credentials' switch was present!"
                exit
            }
        }
        else {
            $Credential = Import-CliXml -Path $File
        }
    }
        
    #check if we should cache if it's not yet cached
    If($Name -and !$script:CachedCredentials.ContainsKey($Name)) {
        if(!$ShowedCredentialDialog -and !$Credential) {
            if(!$NoInput.IsPresent -or $Init.IsPresent) {
                $Credential = Get-CredentialInternal -Message $Message -Usage $Usage -NoOutput:$NoOutput
            }
            $ShowedCredentialDialog = $true
        }

        if($Credential) {
            $script:CachedCredentials[$Name] = $Credential
        }
    }

    #now if no file or cache name was given, this will finally prompt us to enter credentials
    if(!$NoUnstored.IsPresent -and !$Credential -and !$NoInput.IsPresent -and !$ShowedCredentialDialog) {
        $Credential = Get-CredentialInternal -Message $Message -Usage $Usage -NoOutput:$NoOutput
        $ShowedCredentialDialog = $true
    }

    if($ErrorOnNone.IsPresent -and !$Credential) {
        if(!$NoUnstored.IsPresent -or $File -or $Name) {
            $strMessage = "Credentials could not be initialized or retrieved"
            if($Usage) {
                $strMessage = "Credentials for $Usage could not be initialized or retrieved"
            }
            throw $strMessage            
        }
    }

    return $Credential
}

function Use-NetworkCredential {
    <#
        .SYNOPSIS
            Gets Network credentials from a cache, file or user input (in that order) and save it to a file and cache.
            If file and/or cache will be used to store the credentials can be configured.
            The credentials will be cached and/or saved to a file as PS credentials. So this method can also be used
            to retrieve these credentials as PS credentials later, or retrieve the network credentials of previously
            stored PS credentials.
        .PARAMETER Name
            Unique cache name for the credentials.
            If no cache name is provided, the credentials will not be cached.
        .PARAMETER File
            File to store credentials in and read credentials from.
            Information will be stored in the XML file format.
            If no path for a credentials file was provided this method will not save the credentials to a file.
        .PARAMETER Message
            Message to prompt for credential input.
            Default is "Please enter credentials"
        .PARAMETER Usage
            Optional string describing the usage for the credentials (will be appended to "Initializing credentials for <$Usage>").
            This will be ignored if the -NoOuptut switch was provided.
        .PARAMETER ErrorOnNone
            True/Present...Will throw an error if no credentials were found (even though File or Name was given in case of NoUnstored switch present)
        .PARAMETER NoInput
            True/Present...Will expect a name or file path to be provided and for there to already be a stored credential (exception: Init switch)
        .PARAMETER NoUnstored
            True/Present...Will not ask for credentials if no file path or cache name was provided
        .PARAMETER Init
            True/Present...If the File parameter was provided:
                            The script will ask for the credentials to use, store them in a credentials file and will then immediatly exit the script.
                            Used to either set up credentials file for the first time, or change/renew the credentials in the credential file, without performing the
                            actual task by the script. The -WhatIf switch cannot be used to make sure the script is not performing its task, because it will also prevent
                            the script from saving the credentials to the credentials file.
                            This switch is ignored if the CredentialsFile parameter is not provided.
                            If the Name parameter was provided:
                            Will clear the cache of these credentials and ask for a user input of credentials.
        .PARAMETER NoOutput
            True/Present...Will not display any messages to the host (except if canceling execution due to Init switch being present)
        .OUTPUTS
            Retrieved network credentials object or null
    #>


    [CmdletBinding()]
    PARAM (
        [Parameter(Position=0)]
        [string] $Name = $null,
        [Parameter(Position=1)]
        [string] $File = $null,
        [Parameter(Position=2)]
        [string] $Message = "Please enter credentials",
        [Parameter(Position=3)]
        [string] $Usage = $null,
        [Parameter(Position=4)]
        [switch] $ErrorOnNone,
        [Parameter(Position=5)]
        [switch] $NoInput,
        [Parameter(Position=6)]
        [switch] $NoUnstored,
        [Parameter(Position=7)]
        [switch] $Init,
        [Parameter(Position=8)]
        [switch] $NoOutput
    )

    $PSCredential = Use-PSCredential -Name $Name -File $File -Message $Message -Usage $Usage -ErrorOnNone:$ErrorOnNone -NoInput:$NoInput -NoUnstored:$NoUnstored -Init:$Init -NoOutput:$NoOutput

    if($PSCredential) {
        return [System.Net.NetworkCredential] $PSCredential
    }
    else {
        return $null
    }
}

function Clear-CredentialCache {
    <#
        .SYNOPSIS
            Clears the credential cache (of all or one specific credential).
            Needed at the beginning of a script, if the credentials should be entered again for each execution of the script,
            even if the script is still in the same scope (PS window).
        .PARAMETER Name
            Name of the credentials to remove from cache, or empty if the whole cache should be cleared
        .PARAMETER NoOutput
            True/Present...Will not display any messages to the host
        .OUTPUTS
            Nothing
    #>

    
    [CmdletBinding()]
    PARAM (
        [Parameter(Position=0)]
        [string] $Name,
        [Parameter(Position=1)]
        [switch] $NoOutput
    )
    
    if($Name) {
        if($script:CachedCredentials.ContainsKey($Name)) {
            if(!$NoOutput.IsPresent) {
                Write-Host "Clearing cache of credentials ""$Name""..."
            }
            $script:CachedCredentials.Remove($Name)
            [System.GC]::Collect()
        }
    }
    else {
        if(!$NoOutput.IsPresent) {
            Write-Host "Clearing credentials cache..."
        }
        $script:CachedCredentials = @{}
        [System.GC]::Collect()
    }
}