Module/Rule/Rule.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
381
382
383
384
385
386
387
388
389
390
391
392
393
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
using module .\..\Common\Common.psm1

$exclude = @($MyInvocation.MyCommand.Name,'Template.*.txt', '*.md', '*.psm1', 'data.*.ps1')
$supportFileList = Get-ChildItem -Path $PSScriptRoot -Recurse -File -Exclude $exclude
foreach ($supportFile in $supportFileList)
{
    Write-Verbose "Loading $($supportFile.FullName)"
    . $supportFile.FullName
}
#header

<#
    .SYNOPSIS
        The base class for all STIG rule types
    .DESCRIPTION
        The base class for all STIG rule types to support a common initializer and
        set of methods that apply to all rule types. PowerShell does not support
        abstract classes, but this class is not intended to be used directly.
    .PARAMETER Id
        The STIG ID
    .PARAMETER Title
        Title string from STIG
    .PARAMETER Severity
        Severity data from STIG
    .PARAMETER ConversionStatus
        Module processing status of the raw string
    .PARAMETER RawString
        The raw string from the check-content element of the STIG item
    .PARAMETER SplitCheckContent
        The raw check string split into multiple lines for pattern matching
    .PARAMETER IsNullOrEmpty
        A flag to determine if a value is supposed to be empty or not.
        Some items should be empty, but there needs to be a way to validate that empty is on purpose.
    .PARAMETER OrganizationValueRequired
        A flag to determine if a local organizational setting is required.
    .PARAMETER OrganizationValueTestString
        A string that can be invoked to test the chosen organizational value.
    .PARAMETER DscResource
        Defines the DSC resource used to configure the rule
#>

class Rule : ICloneable
{
    [string] $Id
    [string] $LegacyId
    [string] $Title
    [severity] $Severity
    [status] $ConversionStatus
    [string] $DscResource
    [string] $DuplicateOf
    [string] $Description
    [Boolean] $IsNullOrEmpty
    [Boolean] $OrganizationValueRequired
    [string] $OrganizationValueTestString
    [string] $RawString
    hidden [string[]] $SplitCheckContent

    <#
        .SYNOPSIS
            Default constructor
        .DESCRIPTION
            This is the base class constructor
    #>

    Rule ()
    {
    }

    <#
        .SYNOPSIS
            PowerSTIG XML deserialze constructor
        .DESCRIPTION
            This constructor laods all properties from from the calling child
            class the PowerSTIG XML
        .PARAMETER Rule
            The STIG rule to load from PowerSTIG processed data
    #>

    Rule ([xml.xmlelement] $Rule)
    {
        $propertyList = ($this | Get-Member -MemberType Properties).Name

        foreach ($property in $propertyList)
        {
            if ( -not [string]::IsNullOrEmpty($Rule.($property)) )
            {
                $this.($property) = $Rule.($property)
            }
            if ($property -eq 'OrganizationValueRequired')
            {
                # When a bool is evaluated if anything exists it is true, so we need provide a bool
                $this.OrganizationValueRequired = ($Rule.OrganizationValueRequired -eq 'true')
            }
        }
    }

    <#
        .SYNOPSIS
            XCCDF XML constructor
        .DESCRIPTION
            This is the base class constructor
    #>

    Rule ([xml.xmlelement] $Rule, [switch] $Convert)
    {
        $this.Id = $Rule.Id
        $this.LegacyId = ($rule.Rule.ident | Where-Object -FilterScript {$PSItem.'#text' -match "^V-.*"}).'#text'
        $this.Title = $Rule.Title
        $this.Severity = $Rule.rule.severity
        $this.Description = $Rule.rule.description
        if (Test-HtmlEncoding -CheckString  $Rule.rule.Check.('check-content'))
        {
            $this.RawString = (ConvertFrom-HtmlEncoding -CheckString $Rule.rule.Check.('check-content'))
        }
        else
        {
            $this.RawString = $Rule.rule.Check.('check-content')
        }

        $this.SplitCheckContent = [Rule]::SplitCheckContent($this.rawString)
        $this.IsNullOrEmpty = $false
        $this.OrganizationValueRequired = $false
        $this.SetLegacyId($Rule)
    }

    #region Methods

    <#
        This method is needed in each convert class for a couple of reasons.
        1. PSTypeConverter has to be implemented at a .NET type, which might cause issues with customers that use constrained language mode.
        2. The parent class modules cannot load the child class modules (load loop)
    #>

    hidden [psobject] AsRule()
    {
        # Create an instance of the convert rule parent class
        $parentRule = $this.GetType().BaseType::new()
        # Get the property list from the convert rule
        $propertyList = $this | Get-Member -MemberType Properties
        # Copy the convert properties to the parent properties
        foreach ($property in $propertyList)
        {
            if ( $null -ne $this.($property.Name) )
            {
                $parentRule.($property.Name) = $this.($property.Name)
            }
        }
        return $parentRule
    }

    <#
        .SYNOPSIS
            Returns the rule property to override based on the override tag
    #>

    hidden [string] GetOverrideValue()
    {
        # The path that is returned from GetType contains wierd backslashes that I can't figure out how to use.
        $moduleName = $this.GetType().Name -replace 'Rule', ''
        $baseclassPath = Resolve-Path -Path "$PSScriptRoot\..\Rule.$moduleName\$($this.GetType().Name).psm1"
        # Exception property tag is used in the base class to identify the property that is to be overridden
        # the patteren is as follows
        # [type] $Name <#(ExceptionValue)#>
        $exceptionPropertyTag = '\s+(?:\[\w+(?:\[\s*\])?\])\s\$(?<ExceptionValue>\w+)\s+<#\(ExceptionValue\)#>'
        $exceptionProperty = [regex]::Matches(
            (Get-Content -path $baseclassPath -raw), $exceptionPropertyTag
        ).Groups.Where( {$_.Name -eq 'ExceptionValue'}).Value

        return $exceptionProperty
    }

    <#
        .SYNOPSIS
            Applies an org setting to a rule
    #>

    [void] AddOrgSetting ([hashtable] $OrgSettingParamValue)
    {
        foreach ($key in $OrgSettingParamValue.Keys)
        {
            $this.$key = $OrgSettingParamValue[$key]
        }
    }

    <#
        .SYNOPSIS
            Applies an exception to a rule
    #>

    [void] AddExceptionToPolicy ([object] $ExceptionParamValue)
    {
        $this.UpdateRuleTitle('Exception')
        if ($ExceptionParamValue -is [hashtable])
        {
            foreach ($key in $ExceptionParamValue.Keys)
            {
                $this.$key = $ExceptionParamValue[$key]
            }
        }
        else
        {
            $this.($this.GetOverrideValue()) = $ExceptionParamValue
        }
    }

    <#
    .SYNOPSIS
        Applies a uniform title update format
    #>

    [void] UpdateRuleTitle ([string] $Value)
    {
        $this.Title = "[$Value] " + $this.Title
    }

    <#
        .SYNOPSIS
            Creates a shallow copy of the current object
    #>

    hidden [Object] Clone ()
    {
        return $this.MemberwiseClone()
    }

    <#
        .SYNOPSIS
            Tests if the rule already exists
        .DESCRIPTION
            Compares the rule with existing converted rules
        .PARAMETER ReferenceObject
            The existing converted rules
    #>

    hidden [void] SetDuplicateRule ()
    {
        $val = Test-DuplicateRule -ReferenceObject $global:stigSettings -DifferenceObject $this
        if ($val)
        {
           $this.DuplicateOf = $val
        }
    }

    <#
        .SYNOPSIS
            Sets the conversion status
        .DESCRIPTION
            Sets the conversion status
        .PARAMETER Value
            The value to be tested
    #>

    hidden [Boolean] SetStatus ( [String] $Value )
    {
        if ( [String]::IsNullOrEmpty( $Value ) )
        {
            $this.conversionstatus = [status]::fail
            return $true
        }
        else
        {
            return $false
        }
    }

    <#
        .SYNOPSIS
            Sets the conversion status with an allowed blank value
        .DESCRIPTION
            Sets the conversion status with an allowed blank value
        .PARAMETER Value
            The value to be tested
        .PARAMETER AllowNullOrEmpty
            A flag to allow blank values
    #>

    hidden [Boolean] SetStatus ( [String] $Value, [Boolean] $AllowNullOrEmpty )
    {
        if ( [String]::IsNullOrEmpty( $Value ) -and -not $AllowNullOrEmpty )
        {
            $this.conversionstatus = [status]::fail
            return $true
        }
        else
        {
            return $false
        }
    }

    <#
        .SYNOPSIS
            Sets the IsNullOrEmpty value to true
        .DESCRIPTION
            Sets the IsNullOrEmpty value to true
    #>

    hidden [void] SetIsNullOrEmpty ()
    {
        $this.IsNullOrEmpty = $true
    }

    <#
        .SYNOPSIS
            Sets the OrganizationValueRequired value to true
        .DESCRIPTION
            Sets the OrganizationValueRequired value to true
    #>

    hidden [void] SetOrganizationValueRequired ()
    {
        $this.OrganizationValueRequired = $true
    }

    <#
        .SYNOPSIS
            Gets the organization value test string
        .DESCRIPTION
            Gets the organization value test string
        .PARAMETER TestString
            The string to extract the
    #>

    hidden [string] GetOrganizationValueTestString ( [String] $TestString )
    {
        return Get-OrganizationValueTestString -String $TestString
    }

    <#
        .SYNOPSIS
            Converts the object into a hashtable
        .DESCRIPTION
            Converts the object into a hashtable
    #>

    <#{TODO}#> # remove and cleanup testhelper.psm1
    hidden [hashtable] ConvertToHashTable ()
    {
        return ConvertTo-HashTable -InputObject $this
    }

    <#
        .SYNOPSIS
            Splits the check-content element in the xccdf into an array
        .DESCRIPTION
            Splits the check-content element in the xccdf into an array
        .PARAMETER CheckContent
            The rule text from the check-content element in the xccdf
    #>

    hidden static [string[]] SplitCheckContent ( [String] $CheckContent )
    {
        return (
            $CheckContent -split '\n' |
                Select-String -Pattern "\w" |
                ForEach-Object { $PSitem.ToString().Trim() }
        )
    }

    <#
        .SYNOPSIS
            Get the fixtext from the xccdf
        .DESCRIPTION
            Get the fixtext from the xccdf
        .PARAMETER StigRule
            The StigRule to extract the fix text from
    #>

    hidden static [string[]] GetFixText ( [xml.xmlelement] $StigRule )
    {
        $fullFix = $StigRule.Rule.fixtext.'#text'

        $return = $fullFix -split '\n' |
            Select-String -Pattern "\w" |
            ForEach-Object { $PSitem.ToString().Trim() }

        return $return
    }

    <#
        .SYNOPSIS
            Looks for the rule to see if it already exists
        .DESCRIPTION
            Looks for the rule to see if it already exists
        .PARAMETER RuleCollection
            The global rule collection
    #>

    hidden [bool] IsExistingRule ( [object] $RuleCollection )
    {
        return Test-ExistingRule -RuleCollection $RuleCollection $this
    }

    #endregion
    #region Hard coded Methods

    <#
        .SYNOPSIS
            Sets the LegacyId from the raw xccdf xml (DISA Changes October 2020)
        .DESCRIPTION
            Sets the LegacyId from the raw xccdf xml (DISA Changes October 2020)
    #>

    hidden [void] SetLegacyId ([xml.xmlelement] $Rule)
    {
        $this.LegacyId = ($Rule.rule.ident | Where-Object -FilterScript {$PSItem.'#text' -match "^V-.*"}).'#text'
        if ($Rule.id -match '^V-.*\.[a-z]$' -and [string]::IsNullOrEmpty($this.LegacyId) -eq $false)
        {
            $this.LegacyId = '{0}.{1}' -f $this.LegacyId, $Rule.id.Split('.')[1]
        }
    }
}