lib/TMD.Credentials.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
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
function Add-StoredCredential {
    <#
    .SYNOPSIS
    Stores the given credential on the local hard drive

    .DESCRIPTION
    Exports the given credential object to an XML file which is saved in the TMD_Files directory

    .PARAMETER Name
    The name to be used when referencing the stored credential

    .PARAMETER Credential
    The credential object to be stored

    .PARAMETER Passthru
    Returns the PSCredential object created and stored with the Name provided

    .EXAMPLE
    Get-Credential | Add-StoredCredential -Name 'MyCreds'

    .OUTPUTS
    None
    #>


    [CmdletBinding()]
    [Alias('New-StoredCredential')]
    param(
        [CmdletBinding()]
        [Parameter(Mandatory = $true,
                   Position = 0,
                   ValueFromPipeline = $true,
                   ValueFromPipelineByPropertyName = $true)]
        [Alias('CredentialName')]
        [String]$Name,

        [Parameter(Mandatory = $false,
                   Position = 1,
                   ValueFromPipelineByPropertyName = $true)]
        [PSCredential]$Credential,

        ## Allow returning the PSCredential Object (useful when prompted for new)
        [switch]$Passthru
    )

    process {
        if (!$Credential) {
            if (Test-TMDIsRunningAction) {
                $ErrorRecord = [System.Management.Automation.ErrorRecord]::new(
                    [Exception]::new("A Credential must be provided"),
                    "TMD.CRED01",
                    [System.Management.Automation.ErrorCategory]::InvalidArgument,
                    $null
                )
                $PSCmdlet.WriteError($ErrorRecord)
            }
            else {
                $Credential = (Get-Credential)
            }
        }
        $CredentialFilePath = Join-Path $Global:UserPaths.Credentials ($Name + '.credential')
        Export-Clixml -InputObject $Credential -Path $CredentialFilePath

        ## Return the PSCredential Object
        if($Passthru.isPresent){
            $Credential
        }
    }
}
Set-Alias -Name 'New-StoredCredential' -Value 'Add-StoredCredential' -Option AllScope -Scope Global


function Remove-StoredCredential {
    <#
    .SYNOPSIS
    Removes a previously stored credential from the local hard drive

    .DESCRIPTION
    Overwrites a stored .credential file multiple times with a random bytestream before deleting
    it from the local hard drive

    .PARAMETER Name
    The name of the credential to be removed

    .PARAMETER OverwriteCount
    The number of times to overwrite the file before removing it

    .EXAMPLE
    Remove-StoredCredential -Name 'MyCreds'

    .EXAMPLE
    Get-StoredCredential | Remove-StoredCredential

    .OUTPUTS
    None
    #>


    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true,
                   ValueFromPipeline = $true,
                   ValueFromPipelineByPropertyName = $true)]
        [Alias('CredentialName')]
        [ArgumentCompleter({ Get-StoredCredential -List })]
        [String]$Name,

        [Parameter(Mandatory = $false)]
        [Int]$OverwriteCount = 500
    )

    process {
        $CredentialFilePath = Join-Path -Path $Global:UserPaths.Credentials ($Name + '.credential')
        Write-Verbose "Processing file '$CredentialFilePath'"
        if (Test-Path -PathType Leaf -Path $CredentialFilePath) {
            $BufferSize = $Name.Length
            $RandomDataBuffer = [System.Byte[]]::new($BufferSize)

            Write-Verbose "Overwriting the data within the file $OverwriteCount time(s)"
            for ($i = 0; $i -lt $OverwriteCount; $i++) {
                $Random = [System.Random]::new()
                $Random.NextBytes($RandomDataBuffer) | Set-Content -Path $CredentialFilePath -AsByteStream
            }
            Write-Verbose "Removing the file"
            Remove-Item -Path $CredentialFilePath -Force
        }
        else {
            $ErrorRecord = [System.Management.Automation.ErrorRecord]::new(
                [Exception]::new("A stored credential with the name '$Name' does not exist."),
                "TMD.CRED02",
                [System.Management.Automation.ErrorCategory]::InvalidArgument,
                $CredentialFilePath
            )
            $PSCmdlet.WriteError($ErrorRecord)
        }
    }
}

function Get-StoredCredential {
    <#
    .SYNOPSIS
    Gets the specified credential that is stored on the local hard drive

    .DESCRIPTION
    This function either retrieves a specified credential or a list of all stored credentials

    .PARAMETER Name
    The name of the credential to get

    .PARAMETER List
    Switch specifying that a list of the credentials stored on the local hard drive should be returned

    .EXAMPLE
    $StoredCredential = Get-StoredCredential -Name 'MyCreds'

    .OUTPUTS
    A PSCredential object containing the specified credential
    #>


    [CmdletBinding(DefaultParameterSetName = "Single")]
    param(
        [Parameter(Mandatory = $false,
                   Position = 0,
                   ValueFromPipeline = $true,
                   ValueFromPipelineByPropertyName = $true,
                   ParameterSetName = "Single")]
        [ArgumentCompleter({ Get-StoredCredential -List })]
        [Alias('CredentialName')]
        [String]$Name,

        [Parameter(Mandatory = $false, ParameterSetName = "List")]
        [switch]$List
    )

    process{
        try {
            if (-not $Name -or $List) {
                $CredentialFolderPath = Resolve-Path $Global:UserPaths.Credentials
                $CredentialList = Get-ChildItem -Path $CredentialFolderPath -File
                $CredentialList | ForEach-Object {
                    if ($List) {
                        $_.Name -replace $_.Extension, ''
                    }
                    else {
                        [PSCustomObject]@{
                            Name = $_.Name.Replace($_.Extension, '')
                            Credential = Import-Clixml -Path $_.FullName
                        }
                    }
                }
            }
            else {
                $CredentialFilePath = Join-Path $Global:UserPaths.Credentials ($Name + '.credential')
                if (Test-Path -Path $CredentialFilePath) {
                    Import-Clixml -Path $CredentialFilePath
                }
            }
        }
        catch {
            $PSCmdlet.WriteError($_)
        }
    }
}

function Copy-StoredCredential {
    <#
    .SYNOPSIS
    Copies a stored credential

    .DESCRIPTION
    This function copies a StoredCredential from the -ExistingCredentialName to -NewCredentialName

    .PARAMETER ExistingCredentialName
    The name of the source StoredCredentail to copy

    .PARAMETER NewCredentialName
    The name of the new StoredCredential to create

    .PARAMETER Passthru
    Returns the new credential

    .EXAMPLE
    Copy-StoredCredential -ExistingCredentialName 'TMServer' -NewCredentialName 'NewTMServer'

    .EXAMPLE
    Copy-StoredCredential -ExistingCredentialName 'TMServer' -NewCredentialName 'NewTMServer' -Passthru

    .OUTPUTS
    When Passthru is used, a PSCredential is returned
    #>


    [CmdletBinding()]      # Always add CmdletBinding to expose the common Cmdlet variables
    [OutputType([Bool])]   # Add this if the function has an output
    param(
        ## TODO: Add an Argument Completer. This will require additional work on the Get- command to allow matching.
        [Parameter(Mandatory = $true, Position = 0)]
        [ValidateScript({$_ -in (Get-StoredCredential -List)})]
        [String]$ExistingCredentialName,

        [Parameter(Mandatory = $true, Position = 1)]
        [String]$NewCredentialName,

        [Switch]$Passthru
    )

    ## Get and Set the Credential
    $PSCredential = Get-StoredCredential -Name $ExistingCredentialName
    Add-StoredCredential -Name $NewCredentialName -Credential $PSCredential

    ## Return the credential if desired
    if($Passthru){
        return $PSCredential
    }


}


function Test-IsAdmin {
    <#
    .SYNOPSIS
    Checks if the current user has administrative rights

    .EXAMPLE
    $Message = Test-IsAdmin ? "User is an administrator" : "User is not an administrator"
    Write-Host $Message

    .OUTPUTS
    True if the current user is in the Administrators group, otherwise false
    #>

    [CmdletBinding()]

    $user = [Security.Principal.WindowsIdentity]::GetCurrent();
    [Security.Principal.WindowsPrincipal]::new($user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}