Module/Rule.nxFileLine/Convert/Methods.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
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
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

<#
    .SYNOPSIS
        Retrieves the nxFileLineContainsLine from the check-content element in the xccdf
 
    .PARAMETER FixText
        Specifies the FixText element in the xccdf
#>

function Get-nxFileLineContainsLine
{
    [CmdletBinding()]
    [OutputType([string[]])]
    param
    (
        [Parameter(Mandatory = $true)]
        [string[]]
        $CheckContent
    )

    Write-Verbose "[$($MyInvocation.MyCommand.Name)]"
    try
    {
        $rawString = $CheckContent -join "`n"
        if
        (
            $rawString -match $regularExpression.nxFileLineContainsLine -or
            $rawString -match $regularExpression.nxFileLineContainsLineYumConf -or
            $rawString -match $regularExpression.nxFileLineContainsLineAuditUbuntu
        )
        {
            $matchResults = $Matches['setting'] -split "`n"
            $results = @()
            foreach ($line in $matchResults)
            {
                if
                (
                    [string]::IsNullOrEmpty($line) -eq $false -and
                    $line -notmatch $regularExpression.nxFileLineContainsLineExclude
                )
                {
                    $results += $line -replace '\s{2,}', ' '
                }
            }
        }
        elseif ($rawString -match 'You are accessing a U.S. Government \(USG\) [^"]+(?<=details.)')
        {
            $results = $matches.Values -replace '\.\r|:\r', ".`n"
        }

        return $results
    }
    catch
    {
        Write-Verbose "[$($MyInvocation.MyCommand.Name)] nxFileLineContainsLine : Not Found"
        return $null
    }
}

<#
    .SYNOPSIS
        Retreives the nxFileLineFilePath from the check-content element in the xccdf
 
    .PARAMETER FixText
        Specifies the check-content element in the xccdf
#>

function Get-nxFileLineFilePath
{
    [CmdletBinding()]
    [OutputType([string])]
    param
    (
        [Parameter(Mandatory = $true)]
        [string]
        $CheckContent
    )

    try
    {
        $nxFileLineFilePathAggregate = '{0}|{1}|{2}|{3}|{4}|{5}|{6}' -f
            $regularExpression.nxFileLineFilePathAudit,
            $regularExpression.nxFileLineFilePathAuditUbuntu,
            $regularExpression.nxFileLineFilePathUbuntuBanner,
            $regularExpression.nxFileLineFilePathBannerUbuntu,
            $regularExpression.nxFileLineFilePathTftp,
            $regularExpression.nxFileLineFilePathRescue,
            $regularExpression.nxFileLineFilePath
        $null = $CheckContent -match $nxFileLineFilePathAggregate
        switch ($Matches.Keys)
        {
            {
                $PSItem -eq 'auditPath' -or $PSItem -eq 'auditPathUbuntu'
            }
            {
                return '/etc/audit/rules.d/audit.rules'
            }
            'ubuntuBanner'
            {
                return '/etc/issue'
            }
            'bannerPathUbuntu'
            {
                return $Matches['bannerPathUbuntu']
            }
            'tftpPath'
            {
                return $Matches['tftpPath']
            }
            'rescuePath'
            {
                return $Matches['rescuePath']
            }
            'filePath'
            {
                return $Matches['filePath']
            }
            default
            {
                Write-Verbose "[$($MyInvocation.MyCommand.Name)] nxFileLineFilePath : Not Found"
                return $null
            }
        }
    }
    catch
    {
        Write-Verbose "[$($MyInvocation.MyCommand.Name)] nxFileLineFilePath : Not Found"
        return $null
    }
}

<#
    .SYNOPSIS
        Retreives the nxFileLineDoesNotContainPattern from the
        check-content element in the xccdf
 
    .PARAMETER FixText
        Specifies the check-content element in the xccdf
#>

function Get-nxFileLineDoesNotContainPattern
{
    [CmdletBinding()]
    [OutputType([string])]
    param()

    $doesNotContainPatternExclusionRuleId = @(
        'V-71863'
    )

    if ($doesNotContainPatternExclusionRuleId -contains $this.Id)
    {
        return 'PatternNotRequired'
    }

    try
    {
        if ($doesNotContainPattern.ContainsKey($this.ContainsLine))
        {
            $results = $doesNotContainPattern[$this.ContainsLine]
        }

        if
        (
            $results -eq 'DynamicallyGeneratedDoesNotContainPattern' -or
            $doesNotContainPattern.ContainsKey($this.ContainsLine) -eq $false
        )
        {
            <#
                The "Dynamic" DoesNotContainPattern generation takes the containsLine and prefixes it with
                a hash, as well as replaces any spaces with a RegEx \s*.
            #>

            $doesNotContainPattern = $this.ContainsLine -replace '=', '\s*=\s*' -replace '\s+', '\s*'
            $doesNotContainPattern = $doesNotContainPattern.Replace('\s*\s*', '\s*')
            $results = '#\s*{0}' -f $doesNotContainPattern
        }
    }
    catch
    {
        Write-Verbose "[$($MyInvocation.MyCommand.Name)] nxFileLineDoesNotContainPattern : Not Found"
        return $null
    }

    return $results
}

<#
    .SYNOPSIS
        There are several rules that publish multiple FileLine settings in a single rule.
        This function will check for multiple entries.
 
    .PARAMETER CheckContent
        The standard check content string to look for duplicate entries.
#>

function Test-nxFileLineMultipleEntries
{
    [CmdletBinding()]
    [OutputType([bool])]
    param
    (
        [Parameter(Mandatory = $true)]
        [psobject]
        $CheckContent
    )

    $filePath = $CheckContent | Select-String -Pattern $regularExpression.nxFileLineFilePath -AllMatches
    $filePathCount = @()
    foreach ($path in $filePath.Matches)
    {
        if ($path.Groups['filePath'].Value -ne '/etc/issue')
        {
            $filePathCount += $path.Groups['filePath'].Value
        }
    }

    $filePathUniqueCount = $filePathCount | Select-Object -Unique | Measure-Object
    if ($filePathUniqueCount.Count -gt 1)
    {
        return $true
    }

    $splitCheckContent = Split-nxFileLineMultipleEntries -CheckContent $CheckContent
    if ($splitCheckContent.Count -gt 1)
    {
        return $true
    }

    return $false
}

<#
    .SYNOPSIS
        There are several rules that publish multiple FileLine settings in a single rule.
        This function will split multiple entries.
 
    .PARAMETER CheckContent
        The standard check content string to look for duplicate entries.
#>

function Split-nxFileLineMultipleEntries
{
    [CmdletBinding()]
    [OutputType([System.Collections.ArrayList])]
    param
    (
        [Parameter(Mandatory = $true)]
        [psobject]
        $CheckContent
    )

    $splitCheckContent = @()

    # Split CheckContent based on File Path or 'sudo auditctl...':
    $splitFilePathPatternAggregate = '{0}|{1}' -f $regularExpression.nxFileLineFilePath, $regularExpression.nxFileLineFilePathAuditUbuntu
    [array] $splitFilePathLineNumber = ($CheckContent | Select-String -Pattern $splitFilePathPatternAggregate).LineNumber

    # Header for the rule should start at 0 through the first detected file path subtract 2 since Select-String LineNumber is not 0 based
    $headerLineRange = 0..($splitFilePathLineNumber[0] - 2)
    $headerFileLine = $CheckContent[$headerLineRange]

    # Footer should start from the last detected "If" to the end of CheckContent
    [array] $footerDetection = ($CheckContent | Select-String -Pattern $regularExpression.nxFileLineFooterDetection).LineNumber
    $footerLineRange = ($footerDetection[-1] - 1)..($CheckContent.Count - 1)
    $footerFileLine = $CheckContent[$footerLineRange]

    # Putting it all together and returning separate entries to the next loop
    for ($i = 0; $i -lt $splitFilePathLineNumber.Count; $i++)
    {
        $splitFilePathStringBuilder = New-Object -TypeName System.Text.StringBuilder
        foreach ($headerLine in $headerFileLine)
        {
            [void] $splitFilePathStringBuilder.AppendLine($headerLine)
        }

        # If the index is equal to the 0 based array count then we are at the list item and the range is calculated from the footer
        if ($i -eq ($splitFilePathLineNumber.Count - 1))
        {
            $splitFileLineContentRange = ($splitFilePathLineNumber[$i] - 1)..($footerLineRange[0] - 1)
        }
        else
        {
            # Determine start of next rule and subtract by 2 since Select-String LineNumber is not 0 based
            $splitFileLineContentRange = ($splitFilePathLineNumber[$i] - 1)..($splitFilePathLineNumber[$i + 1] - 2)
        }

        # Insert the split rule contents and add the footer\, then store the string in the collection
        foreach ($line in $CheckContent[$splitFileLineContentRange])
        {
            [void] $splitFilePathStringBuilder.AppendLine($line)
        }

        foreach ($footerLine in $footerFileLine)
        {
            [void] $splitFilePathStringBuilder.AppendLine($footerLine)
        }

        $splitCheckContent += $splitFilePathStringBuilder.ToString()
    }

    # Split modified CheckContent based each File Path Setting:
    $splitEntries = @()
    foreach ($content in $splitCheckContent)
    {
        $fileContainsLine = Get-nxFileLineContainsLine -CheckContent $content
        if ($null -ne $fileContainsLine)
        {
            if ($fileContainsLine -match 'You are accessing a U.S. Government \(USG\) [^"]+(?<=details.)')
            {
                $splitEntries += $fileContainsLine
            }
            else
            {
                $checkContentData = $content.Replace(($fileContainsLine -join "`n"), '{0}')
                foreach ($setting in $fileContainsLine)
                {
                    $splitEntries += $checkContentData -f $setting
                }
            }
        }
    }

    return $splitEntries
}