DSCHelperFunctions.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
function Install-DSCHelperStores
{
<#
.Synopsis
Simple install function that creates default folders and files if needed
.DESCRIPTION
This functioncreates a certificate storage share and sample passwordXML/dscnodes files for use by the remaining functions. Generally, this will only ever be run once.
.EXAMPLE
Install-DSCHelperStores
 
Creates a new folder in $env:PROGRAMFILES\WindowsPowershell\DscService\"NodeCertficates". "NodeCertificates" is shared. A sample passwords.xml and dscnodes.csv file are created under DscService
.PARAMETER CertStore
The location for the certificates to be placed.
The default path if not defiend is $env:PROGRAMFILES\WindowsPowershell\DscService\NodeCertificates
.PARAMETER PasswordData
The location for the passwordxml file.
The default file is $env:PROGRAMFILES\WindowsPowershell\DscService\passwords.xml
.PARAMETER GUIDData
The location for the dscnodes file.
The default file is $env:PROGRAMFILES\WindowsPowershell\DscService\dscnodes.csv
#>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$false)][Alias("PullServerCertStore")][String]$CertStore = "$env:PROGRAMFILES\WindowsPowershell\DscService\NodeCertificates",
        [Parameter(Mandatory=$false)][Alias("XMLFile")][String]$PasswordData = "$env:PROGRAMFILES\WindowsPowershell\DscService\passwords.xml",
        [Parameter(Mandatory=$false)][Alias("CSVFile")][String]$GUIDData = "$env:PROGRAMFILES\WindowsPowershell\DscService\DSCNodes.csv"
        )

    Begin {
        [bool]$IsValid=$true
        [string]$Domain=(Get-WmiObject -Class Win32_NTDomain).DomainName
        $Domain = $Domain.Trim()
    }#End Begin Block

    Process {
    If($CertStore -and !(Test-Path -Path ($CertStore))) {
        try {
            Write-Verbose "Creating Folder $Certstore"
            New-Item ($CertStore) -type directory -force -ErrorAction STOP | Out-Null

            Write-Verbose "Creating SMB Share"
            New-SmbShare -Name "CertStore" -Path $CertStore -ChangeAccess Everyone | Out-Null

            Write-Verbose "Setting permssions for Domain Computers"
            $acl = get-acl $CertStore
            $inherit = [system.security.accesscontrol.InheritanceFlags]"ContainerInherit, ObjectInherit"
            $propagation = [system.security.accesscontrol.PropagationFlags]"None"
            $rule = new-object System.Security.AccessControl.FileSystemAccessRule("$Domain\Domain Computers","Modify",$inherit,$propagation,"Allow")
            $acl.SetAccessRule($rule)
            set-acl $CertStore $acl
            }
        catch {
            $E = $_.Exception.GetBaseException()
            $E.ErrorInformation.Description
            }
        }#End Create Missing CertStore
    Else {write-verbose "$certstore already exists"}

    If($PasswordData -and !(Test-Path -Path ($PasswordData))) {
        Write-Verbose "File not found, creating dummy file"
        $FilePath = Split-Path $PasswordData
        
        #If missing, create the folder structure
        If (!(Test-Path -Path $FilePath)) {
            Try {
                write-verbose "Creating password parent directory"
                New-Item ($FilePath) -type directory -force -ErrorAction STOP | Out-Null
                }
            Catch {
                $E = $_.Exception.GetBaseException()
                $E.ErrorInformation.Description
                write-verbose "error creating directory $FilePath"
                break
                }
            }#End Parent Folder Creation

        #Try to create the sample xml
        Try {
            Write-Verbose "Creating file $PasswordData"
            $xmlWriter = New-Object System.XMl.XmlTextWriter($PasswordData,$Null)
            #Set Format
            $xmlWriter.Formatting = 'Indented'
            $xmlWriter.Indentation = 1
            $XmlWriter.IndentChar = "`t"
            #Create
            $xmlWriter.WriteStartDocument()
            #Start New Element array
            $xmlWriter.WriteStartElement('Credentials')
            #Add Stuff to it
            $xmlWriter.WriteStartElement('Variable')
            $xmlWriter.WriteAttributeString('Name', 'DomainAdminCredentials')
            $xmlWriter.WriteAttributeString('User','Contoso\Administrator')
            $xmlWriter.WriteAttributeString('Password','Password')
            #End specific Entry
            $xmlWriter.WriteEndElement()
            #End larger element
            $xmlWriter.WriteEndElement()
            #Write to disk and let it go
            $xmlWriter.Flush()
            $xmlWriter.Close()
            }
        Catch {
            write-error "Error creating sample xml File"
            break
            }
        }#End Create Missing PasswordData
    Else {write-verbose "$PasswordData already exists"}

    If($GUIDData -and !(Test-Path -Path ($GUIDData))) {
        Write-Verbose "File not found, creating dummy file"
        $FilePath = Split-Path $GUIDData
        
        #If missing, create the folder structure
        If (!(Test-Path -Path $FilePath)) {
            Try {
                write-verbose "Creating csv parent directory"
                New-Item ($FilePath) -type directory -force -ErrorAction STOP | Out-Null
                }
            Catch {
                $E = $_.Exception.GetBaseException()
                $E.ErrorInformation.Description
                write-verbose "error creating directory $FilePath"
                break
                }
            }#End Parent Folder Creation

        #Try to create the sample csv
        Try {
            Write-Verbose "Creating file $GUIDData"
            #Need to create a custom object to add to the arraylist
            $newentry = new-object PSObject
            $newentry | Add-Member -Type NoteProperty -Name NodeName -Value "Node1"
            $newentry | Add-Member -Type NoteProperty -Name NodeGUID -Value "12345678-1234-1234-1234-1234567890ab"
            $newentry | export-csv -Path $GUIDData -Force
            }
        Catch {
            write-error "Error creating sample csv File"
            break
            }
        }#End Create Missing GUIDData
    Else {write-verbose "$GUIDData already exists"}

    }#End Process Block
}

function Update-ConfigurationDataCertificates
{
<#
.Synopsis
Function that adds Certificate parameters to nodes in a hashtable
.DESCRIPTION
Function is designed to assist DSC automation by dynamically matching nodes in configurationdata with certificates of the same name in a specified directory. The function ouputs a modified hashtable with thumbprint and certificatefile parameters added. When used with the DSCResource cLCMCertManager, it can create a complete Certificate management solution.
.EXAMPLE
$updatedlabhosts = Update-ConfigurationDataCertificates -ConfigurationData $LabHosts
 
The above command takes the configurationdata "$Labhosts" and updates it to include certificate signing information.
.PARAMETER ConfigurationData
The configurationdata hashtable to update.
.PARAMETER CertStore
The path to the current collection of certificates. Certificaets are assumed to be saved with a matching filename to the NodeName (plus .cer).
The default path checked if not defiend is $env:PROGRAMFILES\WindowsPowershell\DscService\NodeCertificates
#>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)][ValidateNotNullOrEmpty()][HashTable]$ConfigurationData,
        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)][Alias("PullServerCertStore")][String]$CertStore = "$env:PROGRAMFILES\WindowsPowershell\DscService\NodeCertificates"
    )

    Begin {
        #Gather Certifcate List from the CertStore, and stage the initial return data
        $FoundCerts = (get-childitem $certstore -File -Filter *.cer).BaseName
        $ReturnData = $ConfigurationData
    }


    Process {
        #Update each Node with certificate information if found
        $ReturnData.AllNodes | ForEach-Object -Process {
        $CurrNode = $_.NodeName
        If (($FoundCerts -contains $CurrNode) -and ($CurrNode -ne "*")) {
            
            #Set the filename
            $CertificateFile = $CertStore+'\'+$CurrNode+'.cer'

            #Create X509Certificate2 object that will represent the certificate, then import into it
            $CertPrint = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2    
            $CertPrint.Import($CertificateFile)
            $Thumbprint = $CertPrint.Thumbprint

            #Update the Record
            If ($Thumbprint) {
                $_.Thumbprint = $Thumbprint
                $_.CertificateFile = $CertificateFile
                }
            Else {
                write-error "There was an error retrieving the certificate thumbprint"
                }
            }
        }#End Per-Object Crawl
    }

    End {
        return $ReturnData
    }
}

function Update-ConfigurationDataPasswords
{
<#
.Synopsis
Function that imports usernames and passwords from an XMLfile and stores them in the "*" node for consumption
.DESCRIPTION
Function is designed to assist DSC automation by importing passwords from an XML file into the wildcard node of a configuration. This allows passwords to be stores seperate from the main configuration script
.EXAMPLE
$updatedlabhosts = Update-ConfigurationDataPasswords -ConfigurationData $LabHosts
 
The above command takes the configurationdata "$Labhosts" and updates it to include all passwords in the password log.
.PARAMETER ConfigurationData
The configurationdata hashtable to update.
.PARAMETER PasswordData
The path to the current password XML file. For guidance, Install-DSCHelperStores can create a "sample".
The default file checked if not defiend is $env:PROGRAMFILES\WindowsPowershell\DscService\passwords.xml
#>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)][ValidateNotNullOrEmpty()][HashTable]$ConfigurationData,
        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)][Alias("XMLFile")][String]$PasswordData = "$env:PROGRAMFILES\WindowsPowershell\DscService\passwords.xml"
    )

    Begin {
        #Load ConfigurationData into memory and execute updates
        $ReturnData = $ConfigurationData
        $Wildcardinjection = $null
    }#End Begin Block

    Process {
        #Seperate Wilcard information from the rest of configuration
        IF ($ReturnData.AllNodes.Where({$_.NodeName -eq "*"})) {
            $Returndata.AllNodes | ForEach-Object { IF ($_.NodeName -eq "*") {$Wildcardinjection= $_}}
            $ReturnData.AllNodes = $ReturnData.AllNodes.Where{($_.NodeName -ne "*")}
            }
        Else {
            #Create Missing Wildcard
            $Wildcardinjection = @{}
            $Wildcardinjection.NodeName = "*"
            }
    
        #Merge Passwords into Wildcard
        $Wildcardinjection+=Import-PasswordXML -XMLFile $PasswordData
        $ReturnData.AllNodes+=$Wildcardinjection
    }#End process block

    End {
        Return $ReturnData
    }
}

function Update-ConfigurationDataNames
{
<#
.Synopsis
Function that imports NodeNames and associated GUIDs from a CSVfile and then updates ConfigurationData accordingly
.DESCRIPTION
Function allows admins to use "friendly" names for nodes, and transltes them into GUIDs for use by DSC. Capable of replacing found translations as well as generating new GUIDs for new entries if flag is set.
.EXAMPLE
$updatedlabhosts = Update-ConfigurationDataNames -ConfigurationData $LabHosts
 
The above command takes the configurationdata "$Labhosts" and updates it to use GUID entries stored in a csv.
.PARAMETER ConfigurationData
The configurationdata hashtable to update.
.PARAMETER GUIDData
The path to the current .csv file. Install-DSCHelperStores can be used to create a file for guidance
The default file checked if not defiend is $env:PROGRAMFILES\WindowsPowershell\DscService\DSCNodes.csv
.PARAMETER Update
Tells the function to generate a new GUID and update the CSV file if a Node is missing
#>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)][ValidateNotNullOrEmpty()][HashTable]$ConfigurationData,
        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)][Alias("CSVFile")][String]$GUIDData = "$env:PROGRAMFILES\WindowsPowershell\DscService\DSCNodes.csv",
        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true)][Switch]$Update = $false
    )

    Begin {
        #Load ConfigurationData and node information into memory
        $ReturnData = $ConfigurationData
        [System.Collections.ArrayList]$DSCNodes = Import-Csv -path $GUIDData
        [bool]$DSCNodesFileNeedsUpdating = $false
    }#End Begin Block

    Process {
        #Check each nodename for an equivelant thumbprint
        $ReturnData.AllNodes | ForEach-Object -Process {
            $OrigName = $_.NodeName
            If ($DSCNodes.NodeName -contains $OrigName) {
                $NewGuid = ($DSCNodes | Where {$_.NodeName -eq $OrigName}).NodeGuid
                $_.NodeName = $NewGuid
                Write-Verbose -Message "Updated $OrigName to $NewGUID"
                }#End Match Found
            ElseIf ($Update -and ($OrigName -ne "*")) {
                $DSCNodesFileNeedsUpdating = $true
                $NewGuid = [string][guid]::NewGuid()
                $_.NodeName = $NewGuid
                #Need to create a custom object to add to the arraylist
                $newentry = new-object PSObject
                $newentry | Add-Member -Type NoteProperty -Name NodeName -Value $OrigName
                $newentry | Add-Member -Type NoteProperty -Name NodeGUID -Value $NewGUID
                $DSCNodes.add($newentry) | Out-Null
                Write-Verbose -Message "created missing entry for $OrigName and $NewGUID"
                }#End update Missing Entry
            }#End crawling each Node
    }#End process block

    End {
        If ($DSCNodesFileNeedsUpdating) {
            Write-Verbose -Message "committing changes to $GUIDData"
            $DSCNodes | export-csv -Path $GUIDData -Force
            }
        Return $ReturnData
    }#End Block
}

Function Import-PasswordXML
{
<#
.Synopsis
Takes the contents of an xml file and either returns credential objects or stores them as variables in the current session
.DESCRIPTION
This function is primarily designed to assist Update-ConfigurationDataPasswords, but is allowed to be called direclty for other uses
.EXAMPLE
Import-PasswordXML -XMLFile "C:\passwords.xml"
 
This will return one pscredential object per username/password combination found in passwords.xml
.EXAMPLE
Import-PasswordXML -XMLFile "C:\passwords.xml" -ToSession
 
This will create pscredential per username/password combination and store it as a varable in the current session.
.PARAMETER XMLFile
The path to the current password XML file. If the file does not exist, the module will attempt to create a "sample" for population.
The default file checked if not defiend is $env:PROGRAMFILES\WindowsPowershell\DscService\passwords.xml
.PARAMETER ToSession
Switch that toggles if the object is returned directly or stored as a variable in the current session
#>

[cmdletBinding()]
param(
    [Parameter(Mandatory=$false)][String]$XMLFile = "$env:PROGRAMFILES\WindowsPowershell\DscService\passwords.xml",
    [Parameter(Mandatory=$false)][Switch]$ToSession
    )

    begin {
        #Check if XMLFile is missing
        IF (!(Test-Path -Path $XMLFile)) {
            Write-Error "File not found, cannot continue"
            Break
            }#End Create XML If
    }#End Begin block

    Process {
        #Generate Password Variables from XMLData
        Write-Verbose -Message "Loading Passwords from xml..."
        $Passwords = @{}
        $Config = [XML](Get-Content $XMLFile)
        $Config.Credentials | ForEach-Object {$_.Variable} | Where-Object {$_.Name -ne $null} | ForEach-Object {
        $SecurePass = ConvertTo-SecureString $_.Password -AsPlainText -Force
        $cred = New-Object System.Management.Automation.PSCredential $_.User, $SecurePass
        If ($ToSession) {    
            $PSCmdlet.SessionState.PSVariable.Set($_.Name, $cred)
            }
        Else {
            $Passwords.add($_.Name, $cred)
            }
        } #End ForEach Loop
    }#End process block

    End {
        #Return Hashtable
        If (!$ToSession) {return $Passwords}
    }#End End Block
}