DSCResources/MSFT_AuditPolicyCsv/MSFT_AuditPolicyCsv.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
Import-Module -Name (Join-Path -Path ( Join-Path -Path ( Split-Path $PSScriptRoot -Parent ) `
                                                 -ChildPath 'AuditPolicyResourceHelper' ) `
                               -ChildPath 'AuditPolicyResourceHelper.psm1')

# Localized messages for Write-Verbose statements in this resource
$script:localizedData = Get-LocalizedData -ResourceName 'MSFT_AuditPolicyCsv'

<#
    .SYNOPSIS
        Gets the current audit policy for the node.
    .PARAMETER CsvPath
        This parameter is ignored in the Get operation, but does return the path to the
        backup of the current audit policy settings.
#>

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([Hashtable])]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateSet('Yes')]
        [String]
        $IsSingleInstance,

        [Parameter(Mandatory = $true)]
        [String]
        $CsvPath
    )

    [String] $tempFile = ([system.IO.Path]::GetTempFileName()).Replace('.tmp','.csv')

    try
    {
        Write-Verbose -Message ($localizedData.BackupFilePath -f $tempFile)
        Invoke-SecurityCmdlet -Action "Export" -CsvPath $tempFile
    }
    catch
    {
        Write-Verbose -Message ($localizedData.ExportFailed -f $tempFile)
    }

    return @{
        CsvPath = $tempFile
        IsSingleInstance = 'Yes'
    }
}

<#
    .SYNOPSIS
        Sets the current audit policy for the node.
    .PARAMETER CsvPath
        Specifies the path to desired audit policy settings to apply to the node.
#>

function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateSet('Yes')]
        [String]
        $IsSingleInstance,

        [Parameter(Mandatory = $true)]
        [String]
        $CsvPath
    )

    if ( Test-Path -Path $CsvPath )
    {
        try
        {
            Invoke-SecurityCmdlet -Action "Import" -CsvPath $CsvPath | Out-Null
            Write-Verbose -Message ($localizedData.ImportSucceeded -f $CsvPath)
        }
        catch
        {
            Write-Verbose -Message ($localizedData.ImportFailed -f $CsvPath)
        }
    }
    else
    {
        Write-Verbose -Message ($localizedData.FileNotFound -f $CsvPath)
    }
}

<#
    .SYNOPSIS
        Tests the current audit policy against the desired policy.
    .PARAMETER CsvPath
        Specifies the path to desired audit policy settings to test against the node.
#>

function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([Boolean])]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateSet('Yes')]
        [String]
        $IsSingleInstance,

        [Parameter(Mandatory = $true)]
        [String]
        $CsvPath
    )

    if ( Test-Path -Path $CsvPath )
    {
        # The CsvPath in Get-TargetResource is ignored and a temp file is returned for comparison.
        $currentAuditPolicyBackupPath = (Get-TargetResource -CsvPath $CsvPath `
                                                            -IsSingleInstance $IsSingleInstance).CsvPath

        $currentAuditPolicy = Import-Csv -Path $currentAuditPolicyBackupPath |
            Select-Object -Property Subcategory, @{
                'Name' = 'Value';
                'Expression' = {$_.'Setting Value'}
            }

        $desiredAuditPolicy = Import-Csv -Path $CsvPath |
            Select-Object -Property Subcategory, @{
                'Name' = 'Value';
                'Expression' = {$_.'Setting Value'}
            }

    # Assume the node is in the desired state until proven false.
    [Boolean] $inDesiredState = $true

    foreach ( $desiredAuditPolicySetting in $desiredAuditPolicy )
    {
        # Get the current setting name that mathches the desired setting name
        $currentAuditPolicySetting = $currentAuditPolicy.Where({
            $_.Subcategory -eq $desiredAuditPolicySetting.Subcategory
        })

        # If the current and desired setting do not match, set the flag to $false
        if ($desiredAuditPolicySetting.Value -ne $currentAuditPolicySetting.Value)
        {
            Write-Warning -Message ($localizedData.testCsvFailed -f
                $desiredAuditPolicySetting.Subcategory)

            $inDesiredState = $false
        }
        else
        {
            Write-Verbose -Message ($localizedData.testCsvSucceed -f
                $desiredAuditPolicySetting.Subcategory)
        }
    }

        # Cleanup the temp file, since it is no longer needed.
        Remove-BackupFile -CsvPath $currentAuditPolicyBackupPath -Verbose

        return $inDesiredState
    }
    else
    {
        Write-Verbose -Message ($localizedData.FileNotFound -f $CsvPath)
        return $false
    }
}

<#
    .SYNOPSIS
        Helper function to use SecurityCmdlet modules if present. If not, go through AuditPol.exe.
    .PARAMETER Action
        The action to take, either Import or Export. Import will clear existing policy before writing.
    .PARAMETER CsvPath
        The path to a CSV file to either create or import.
    .EXAMPLE
        Invoke-SecurityCmdlet -Action Import -CsvPath .\test.csv
#>

function Invoke-SecurityCmdlet
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateSet('Import','Export')]
        [String]
        $Action,

        [Parameter(Mandatory = $true)]
        [String]
        $CsvPath
    )

    # Use the security cmdlets if present. If not, use Invoke-AuditPol to call auditpol.exe.
    if ($null -eq (Get-Module -ListAvailable -Name "SecurityCmdlets"))
    {
        Write-Verbose -Message ($localizedData.CmdletsNotFound)

        if ($Action -ieq "Import")
        {
            Invoke-AuditPol -Command Restore -SubCommand "file:$CsvPath"
        }
        else
        {
            # No force option on Backup, manually check for file and delete it so we can write back again
            if (Test-Path -Path $CsvPath)
            {
                Remove-Item -Path $CsvPath -Force
            }

            Invoke-AuditPol -Command Backup -SubCommand "file:$CsvPath"
        }
    }
    else
    {
        Import-Module -Name SecurityCmdlets

        if ($Action -ieq "Import")
        {
            Restore-AuditPolicy -Path $CsvPath | Out-Null
        }
        elseif ($Action -ieq "Export")
        {
            # No force option on Backup, manually check for file and delete it so we can write back again
            if (Test-Path -Path $CsvPath)
            {
                Remove-Item -Path $CsvPath -Force
            }
            Backup-AuditPolicy -Path $CsvPath | Out-Null
        }
    }
}

<#
    .SYNOPSIS
        Removes the temporary file that is created by the Get\Test functions.
    .PARAMETER CsvPath
        Specifies the path of the temp file to remove.
#>

function Remove-BackupFile
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [String]
        $CsvPath
    )

    try
    {
        Remove-Item -Path $CsvPath
        Write-Verbose -Message ($localizedData.RemoveFile -f $CsvPath)
    }
    catch
    {
        Write-Error $error[0]
    }
}