Framework/Core/AzSKInfo/ComplianceInfo.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
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
using namespace System.Management.Automation
Set-StrictMode -Version Latest 

class ComplianceInfo: CommandBase {    
    hidden [ComplianceMessageSummary[]] $ComplianceMessageSummary = @();
    hidden [ComplianceResult[]] $ComplianceScanResult = @();
    hidden [string] $SubscriptionId
    hidden [bool] $Full
    hidden $baselineControls = @();
    hidden [PSObject] $ControlSettings
    hidden [PSObject] $EmptyResource = @();
    
     
    ComplianceInfo([string] $subscriptionId, [InvocationInfo] $invocationContext, [bool] $full): Base($subscriptionId, $invocationContext) { 
        $this.SubscriptionId = $subscriptionId
        $this.Full = $full
        $this.ControlSettings = $this.LoadServerConfigFile("ControlSettings.json");
    }

    hidden [void] GetComplianceScanData($UseBaselineControls, $UsePreviewBaselineControls) {
        $ComplianceRptHelper = [ComplianceReportHelper]::new($this.SubscriptionContext, $this.GetCurrentModuleVersion());
        $ComplianceReportData = $null
        if ($ComplianceRptHelper.HaveRequiredPermissions() -and -not($UseBaselineControls -or $UsePreviewBaselineControls)) {
            $ComplianceReportData = $ComplianceRptHelper.GetSubscriptionComplianceReport();
            
        }    
        else {
            $selectColumns = New-Object System.Collections.ArrayList;
            $query = "";
            $filterSr = 0
            if ($UsePreviewBaselineControls) {
                $selectColumns.Add('IsPreviewBaselineControl%20eq%20true')
            }
            if ($UseBaselineControls ) {
                $selectcolumns.Add('IsBaselineControl%20eq%20true')
            }
            if (($selectColumns | Measure-Object).Count -gt 0) {
                
                
                $selectColumns.ToArray()| ForEach-Object {
                    if (-not $filterSr) {
                        $query+=$_
                        ++$filterSr
                    }
                    else {
                        
                        $query+="%20or%20"+$_
                        ++$filterSr
                    }
                }
            }
            $ComplianceReportData = $ComplianceRptHelper.GetSubscriptionComplianceReport($query, $null);
        
        }
        
        
        $this.ComplianceScanResult = @();
        if (($ComplianceReportData | Measure-Object).Count -gt 0) {
            $ComplianceReportData | ForEach-Object {                
                $this.ComplianceScanResult += [ComplianceResult]::new($_);
            }
        }
    }
    
    hidden [void] GetComplianceInfo($UseBaselineControls, $UsePreviewBaselineControls) {
        $this.PublishCustomMessage([Constants]::DoubleDashLine, [MessageType]::Default);
        
        $azskConfig = [ConfigurationManager]::GetAzSKConfigData();    
        $settingStoreComplianceSummaryInUserSubscriptions = [ConfigurationManager]::GetAzSKSettings().StoreComplianceSummaryInUserSubscriptions;
        #return if feature is turned off at server config
        if (-not $azskConfig.StoreComplianceSummaryInUserSubscriptions -and -not $settingStoreComplianceSummaryInUserSubscriptions) {
            $this.PublishCustomMessage("NOTE: This feature is currently disabled in your environment. Please contact the cloud security team for your org. ", [MessageType]::Warning);    
            return;
        }        

        $this.PublishCustomMessage([Constants]::DoubleDashLine, [MessageType]::Default);
        $this.PublishCustomMessage("`r`nFetching compliance info for subscription [" + $this.SubscriptionId + "] ...", [MessageType]::Default);
        $this.PublishCustomMessage([Constants]::SingleDashLine, [MessageType]::Default);

        $this.GetComplianceScanData($UseBaselineControls, $UsePreviewBaselineControls);
        if (($this.ComplianceScanResult | Measure-Object).Count -le 0) {
            $this.PublishCustomMessage("No previously persisted compliance data found in the subscription [" + $this.SubscriptionId + "]`nCompliance data will get persisted as you perform scans (or when scans happen from CA/CICD).", [MessageType]::Default);
            return;
        }            
        #$this.GetControlDetails();
        $this.ComputeCompliance();
        $this.GetComplianceSummary($UseBaselineControls, $UsePreviewBaselineControls)
        $this.ExportComplianceResultCSV()
    }


    hidden [void] ComputeCompliance() {
        $this.ComplianceScanResult | ForEach-Object {
            # ToDo: Add condition to check whether control in grace
            if ($_.FeatureName -eq "AzSKCfg" -or $_.VerificationResult -eq [VerificationResult]::Disabled -or $_.VerificationResult -eq [VerificationResult]::Error) {
                $_.EffectiveResult = [VerificationResult]::Skipped
            }
            elseif (-not [string]::IsNullOrEmpty($_.ChildResourceName)) {
                $_.EffectiveResult = [VerificationResult]::Skipped
            }
            else {
                if ($_.VerificationResult -eq [VerificationResult]::Passed) {
                    $_.EffectiveResult = ([VerificationResult]::Passed).ToString();
                    
                    $lastScannedDate = [datetime] $_.LastScannedOn
                    $days = [DateTime]::UtcNow.Subtract($lastScannedDate).Days

                    [int]$allowedDays = [Constants]::ControlResultComplianceInDays
                    
                    if (($null -ne $this.ControlSettings) -and [Helpers]::CheckMember($this.ControlSettings, "ResultComplianceInDays.DefaultControls")) {
                        [int32]::TryParse($this.ControlSettings.ResultComplianceInDays.DefaultControls, [ref]$allowedDays)
                    }
                    if ($_.HasOwnerAccessTag) {
                        if (($null -ne $this.ControlSettings) -and [Helpers]::CheckMember($this.ControlSettings, "ResultComplianceInDays.OwnerAccessControls")) {
                            [int32]::TryParse($this.ControlSettings.ResultComplianceInDays.OwnerAccessControls, [ref]$allowedDays)
                        }
                    }

                    #revert back to actual result if control result is stale
                    if ($days -ge $allowedDays) {
                        $_.EffectiveResult = ([VerificationResult]::Failed).ToString();
                    }                    
                }
                else {
                    $_.EffectiveResult = ([VerificationResult]::Failed).ToString();
                }         
            }            
        }    
    }

    hidden [void] GetComplianceSummary($UseBaselineControls, $UsePreviewBaselineControls) {
        $totalCompliance = 0.0
        $baselineCompliance = 0.0
        $passControlCount = 0
        $passControlCountwithGrace = 0
        $failedControlCount = 0
        $failedControlCountwithGrace = 0
        $baselinePassedControlCount = 0
        $baselinePassedControlCountWithGrace = 0
        $baselineFailedControlCount = 0
        $baselineFailedControlCountWithGrace = 0
        
        $previewBaselinePassedControlCount = 0
        $previewBaselinePassedControlCountWithGrace = 0
        $previewBaselineFailedControlCount = 0
        $previewBaselineFailedControlCountWithGrace = 0

        $attestedControlCount = 0
        $totalControlCount = 0
        $baselineControlCount = 0
        $baselineControlCountWithGrace = 0

        
        $previewBaselineControlCount = 0
        $previewBaselineControlCountWithGrace = 0
        $attestedControlCount = 0
        $gracePeriodControlCount = 0
        $totalComplianceWithGrace = 0.0

        if (($this.ComplianceScanResult | Measure-Object).Count -gt 0) {
            $this.ComplianceScanResult | ForEach-Object {
                $result = $_
                #ideally every proper control should fall under effective result in passed/failed/skipped
                if ($result.EffectiveResult -eq [VerificationResult]::Passed -or $result.EffectiveResult -eq [VerificationResult]::Failed) {
                    # total count has been kept inside to exclude not-scanned and skipped controls
                    $totalControlCount++
                    if ($result.IsControlInGrace -eq $false) {                    
                        if ($result.EffectiveResult -eq [VerificationResult]::Passed) {
                            $passControlCountWithGrace++
                            #baseline controls condition shouldnot increment if it wont fall in passed/ failed state
                            if ($result.IsBaselineControl -eq "True") {
                                $baselineControlCountWithGrace++
                                $baselinePassedControlCountWithGrace++
                            }
                            if ($result.IsPreviewBaselineControl -eq "True") {
                                $previewBaselineControlCountWithGrace++
                                $previewBaselinePassedControlCountWithGrace++
                            }
                        }
                        elseif ($result.EffectiveResult -eq [VerificationResult]::Failed) {
                            $failedControlCountwithGrace++
                            if ($result.IsBaselineControl -eq "True") {
                                $baselineControlCountWithGrace++
                                $baselineFailedControlCountWithGrace++
                            }
                            if ($result.IsPreviewBaselineControl -eq "True") {
                                $previewBaselineControlCountWithGrace++
                                $previewBaselineFailedControlCountWithGrace++
                            }

                        }
                    }
                    else {
                        
                        if ($result.EffectiveResult -eq [VerificationResult]::Passed) {
                            $passControlCount++
                            #baseline controls condition shouldnot increment if it wont fall in passed/ failed state
                            if ($result.IsBaselineControl -eq "True") {
                                $baselineControlCount++
                                $baselinePassedControlCount++
                            }
                            if ($result.IsPreviewBaselineControl -eq "True") {
                                $previewBaselineControlCount++
                                $previewBaselinePassedControlCount++
                            }
                        }
                        elseif ($result.EffectiveResult -eq [VerificationResult]::Failed) {
                            $failedControlCount++
                            if ($result.IsBaselineControl -eq "True") {
                                $baselineControlCount++
                                $baselineFailedControlCount++
                            }
                            if ($result.IsBaselineControl -eq "True") {
                                $previewBaselineControlCount++
                                $previewBaselineFailedControlCount++
                            }

                        }
                    }
                }
                if (-not [string]::IsNullOrEmpty($result.AttestationStatus) -and ($result.AttestationStatus -ne [AttestationStatus]::None)) {
                    $attestedControlCount++
                }
                if ($result.IsControlInGrace -eq $true) {
                    $gracePeriodControlCount++
                }
                
            }
            
            if (($passControlCountwithGrace + $failedControlCountwithGrace) -ne 0) {
                $totalComplianceWithGrace = (100 * $passControlCountwithGrace) / ($passControlCountwithGrace + $failedControlCountwithGrace)
            }
            else {
                $totalComplianceWithGrace = 0;
            }
            
            if (($totalControlCount) -ne 0) {
                $totalCompliance = (100 * ($passControlCountwithGrace + $passControlCount) / $totalControlCount)
            }
            $ComplianceStats = @();
            $summary= @();
            
            if ($UseBaselineControls -and ($baselinePassedControlCountWithGrace + $baselineFailedControlCountWithGrace) -ne 0) {

                $ComplianceStat = "" | Select-Object "ComplianceType",  "Total Passed", "Total Failed" , "Passed (excl. grace)", "Failed (excl. grace)"
                $ComplianceStat.ComplianceType = "Baseline"
                $ComplianceStat."Total Passed" = ($baselinePassedControlCountWithGrace + $baselinePassedControlCount)
                $ComplianceStat."Total Failed" = ($baselineFailedControlCount + $baselineFailedControlCountWithGrace)
                $ComplianceStat."Passed (excl. grace)" = $baselinePassedControlCountWithGrace
                $ComplianceStat."Failed (excl. grace)" =  $baselineFailedControlCountWithGrace
                $ComplianceStats += $ComplianceStat
                
                $summary+="`r`nTotal baseline controls: " + ($baselineControlCount + $baselineControlCountWithGrace)
                
            }
            if ($UsePreviewBaselineControls -and ($previewBaselinePassedControlCountWithGrace + $previewBaselineFailedControlCountWithGrace) -ne 0)
             {
                $ComplianceStat = "" | Select-Object "ComplianceType", "Total Passed", "Total Failed" , "Passed (excl. grace)", "Failed (excl. grace)"
                $ComplianceStat.ComplianceType = "PreviewBaseline"
                $ComplianceStat."Total Passed" +=  ($previewBaselinePassedControlCountWithGrace + $previewBaselinePassedControlCount)
                $ComplianceStat."Total Failed" +=  ($previewBaselineFailedControlCount + $previewBaselineFailedControlCountWithGrace)
                $ComplianceStat."Passed (excl. grace)" += $previewBaselinePassedControlCountWithGrace
                $ComplianceStat."Failed (excl. grace)" += $previewBaselineFailedControlCountWithGrace
                $ComplianceStats += $ComplianceStat
                $summary+="`r`nTotal PreviewBaseline controls: " + ($previewBaselineControlCount + $previewBaselineControlCountWithGrace)
            }                                
            if(-not ($UsePreviewBaselineControls -or $UseBaselineControls )){
                $ComplianceStat = "" | Select-Object "ComplianceType",  "Total Passed", "Total Failed" , "Passed (excl. grace)", "Failed (excl. grace)"
                $ComplianceStat.ComplianceType = "Full"
                $ComplianceStat."Total Passed" += ($passControlCountwithGrace + $passControlCount)
                $ComplianceStat."Total Failed" += ($failedControlCountwithGrace + $failedControlCount)
                $ComplianceStat."Passed (excl. grace)" += ($passControlCountwithGrace)            
                $ComplianceStat."Failed (excl. grace)" += ($failedControlCountwithGrace)
                $ComplianceStats += $ComplianceStat

                
               $summary+= "`r`nTotal controls: " + $totalControlCount
                
            }
                $this.PublishCustomMessage(($ComplianceStats | Format-Table | Out-String  -Width 2048), [MessageType]::Default)
                $this.PublishCustomMessage([Constants]::SingleDashLine, [MessageType]::Default);
                $this.PublishCustomMessage($summary, [MessageType]::Default)
                $this.PublishCustomMessage("`r`nAttested controls: " + $attestedControlCount , [MessageType]::Default);
                $this.PublishCustomMessage("`r`nControls in grace: " + $gracePeriodControlCount , [MessageType]::Default);
                $this.PublishCustomMessage([Constants]::DoubleDashLine, [MessageType]::Default);
                $this.PublishCustomMessage("`r`n`r`n`r`nDisclaimer: Compliance summary/control counts may differ slightly from the central telemetry/dashboard due to various timing/sync lags.", [MessageType]::Default);
       
        }
    }

    hidden [void] GetControlsInGracePeriod() {
        $this.PublishCustomMessage("List of control in grace period", [MessageType]::Default);    
    }

    hidden [void] ExportComplianceResultCSV() {
        $this.ComplianceScanResult | ForEach-Object {
            if ($_.IsBaselineControl -eq "True") {
                $_.IsBaselineControl = "Yes"
            }
            else {
                $_.IsBaselineControl = "No"
            }
            if ($_.IsPreviewBaselineControl -eq "True") {
                $_.IsPreviewBaselineControl = "Yes"
            }
            else {
                $_.IsPreviewBaselineControl = "No"
            }
            if ($_.IsPreviewBaselineControl -eq $true) {
                $_.IsControlInGrace = "Yes"
            }
            else {
                $_.IsControlInGrace = "No"
            }
            if ($_.AttestationStatus.ToLower() -eq "none") {
                $_.AttestationStatus = ""
            }
            if ($_.HasOwnerAccessTag -eq "True") {
                $_.HasOwnerAccessTag = "Yes"
            }
            else {
                $_.HasOwnerAccessTag = "No"
            }
            
            $ControlSeverity = $_.ControlSeverity
            if ([Helpers]::CheckMember($this.ControlSettings, "ControlSeverity.$ControlSeverity")) {
                $_.ControlSeverity = $this.ControlSettings.ControlSeverity.$ControlSeverity
            }
            else {
                $_.ControlSeverity = $ControlSeverity
            }            
        }
        
        

        $objectToExport = $this.ComplianceScanResult
        if (-not $this.Full) {
            $objectToExport = $this.ComplianceScanResult | Select-Object "ControlId", "VerificationResult", "ActualVerificationResult", "FeatureName", "ResourceGroupName", "ResourceName", "ChildResourceName", "IsBaselineControl", "IsPreviewBaselineControl", `
                "ControlSeverity", "AttestationStatus", "AttestedBy", "Justification", "LastScannedOn", "ScanSource", "ScannedBy", "ScannerModuleName", "ScannerVersion", "IsControlInGrace"
        }

        $controlCSV = New-Object -TypeName WriteCSVData
        $controlCSV.FileName = 'ComplianceDetails_' + $this.RunIdentifier
        $controlCSV.FileExtension = 'csv'
        $controlCSV.FolderPath = ''
        $controlCSV.MessageData = $objectToExport

        $this.PublishAzSKRootEvent([AzSKRootEvent]::WriteCSV, $controlCSV);
    }
    
    AddComplianceMessage([string] $ComplianceType, [string] $ComplianceCount, [string] $ComplianceComment) {
        $ComplianceMessage = New-Object -TypeName ComplianceMessageSummary
        $ComplianceMessage.ComplianceType = $ComplianceType
        $ComplianceMessage.ComplianceCount = $ComplianceCount
        $this.ComplianceMessageSummary += $ComplianceMessage
    }
    hidden [void] UpdateStorageComplianceData() {
        $azskConfig = [ConfigurationManager]::GetAzSKConfigData();    
        $settingStoreComplianceSummaryInUserSubscriptions = [ConfigurationManager]::GetAzSKSettings().StoreComplianceSummaryInUserSubscriptions;
        if (-not $azskConfig.StoreComplianceSummaryInUserSubscriptions -and -not $settingStoreComplianceSummaryInUserSubscriptions) {
            $this.PublishCustomMessage("NOTE: This feature is currently disabled in your environment. Please contact the cloud security team for your org. ", [MessageType]::Warning);    
            return;
        }        
        $ComplianceRptHelper = [ComplianceReportHelper]::new($this.SubscriptionContext, $this.GetCurrentModuleVersion());
        $this.PublishCustomMessage("Fetching data from backend. This may take a while...");
        try {
            $message = $ComplianceRptHelper.FetchComplianceStateFromDb();
            $this.PublishCustomMessage($message);
            

        }
        catch {
            [EventBase]::PublishGenericException($_);
        }

    }
}

class ComplianceMessageSummary {
    [string] $ComplianceType = "" 
    [string] $ComplianceCount = ""
    #[string] $ComplianceComment = ""
}

class ComplianceResult {
    [string] $ControlId = ""
    [string] $VerificationResult = ([VerificationResult]::Manual).ToString();
    [string] $ActualVerificationResult = ([VerificationResult]::Manual).ToString();
    [string] $FeatureName = ""
    [string] $ResourceGroupName = ""
    [string] $ResourceName = ""
    [string] $ChildResourceName = ""
    [string] $IsBaselineControl = ""
    [string] $IsPreviewBaselineControl = ""
    [string] $ControlSeverity = ([ControlSeverity]::High).ToString();

    [string] $AttestationCounter = ""
    [string] $AttestationStatus = ""
    [string] $AttestedBy = ""
    [string] $AttestedDate = ""
    [string] $Justification = ""

    [String] $UserComments = ""

    [string] $LastScannedOn = ""
    [string] $FirstScannedOn = ""
    [string] $FirstFailedOn = ""
    [string] $FirstAttestedOn = ""
    [string] $LastResultTransitionOn = ""
    [string] $ScanSource = ""
    [string] $ScannedBy = ""
    [string] $ScannerModuleName = ""
    [string] $ScannerVersion = ""
    [string] $IsControlInGrace ;
    [string] $HasOwnerAccessTag = ""
    [string] $ResourceId = ""
    [string] $EffectiveResult = ([VerificationResult]::NotScanned).ToString();

    ComplianceResult([ComplianceStateTableEntity] $persistedEntity) {
        $this.ControlId = $persistedEntity.ControlId;
        $this.VerificationResult = $persistedEntity.VerificationResult;
        $this.ActualVerificationResult = $persistedEntity.ActualVerificationResult;
        $this.FeatureName = $persistedEntity.FeatureName;
        $this.ResourceGroupName = $persistedEntity.ResourceGroupName;
        $this.ResourceName = $persistedEntity.ResourceName;
        $this.ChildResourceName = $persistedEntity.ChildResourceName;
        $this.IsBaselineControl = $persistedEntity.IsBaselineControl;
        $this.IsPreviewBaselineControl = $persistedEntity.IsPreviewBaselineControl;
        $this.ControlSeverity = $persistedEntity.ControlSeverity;
        $this.AttestationCounter = $persistedEntity.AttestationCounter;
        $this.AttestationStatus = $persistedEntity.AttestationStatus;
        $this.AttestedBy = $persistedEntity.AttestedBy;
        $this.AttestedDate = $persistedEntity.AttestedDate;
        $this.Justification = $persistedEntity.Justification;
        $this.UserComments = $persistedEntity.UserComments;
        $this.LastScannedOn = $persistedEntity.LastScannedOn;
        $this.FirstScannedOn = $persistedEntity.FirstScannedOn;
        $this.FirstFailedOn = $persistedEntity.FirstFailedOn;
        $this.FirstAttestedOn = $persistedEntity.FirstAttestedOn;
        $this.LastResultTransitionOn = $persistedEntity.LastResultTransitionOn;
        $this.ScanSource = $persistedEntity.ScanSource;
        $this.ScannedBy = $persistedEntity.ScannedBy;
        $this.ScannerModuleName = $persistedEntity.ScannerModuleName;
        $this.ScannerVersion = $persistedEntity.ScannerVersion;
        $this.IsControlInGrace = $persistedEntity.IsControlInGrace
        $this.HasOwnerAccessTag = $persistedEntity.HasOwnerAccessTag;
        $this.ResourceId = $persistedEntity.ResourceId;
        #this.$EffectiveResult = if($persistedEntity.VerificationResult;
        
    }

    ComplianceResult($featureName, $resourceId, $resourceGroupName, $resourceName, $controlId, $verificationResult, $isBaselineControl, $isPreviewBaselineControl, $controlSeverity, $effectiveResult) {
        $this.ControlId = $controlId
        $this.FeatureName = $featureName
        $this.VerificationResult = $verificationResult
        $this.ResourceGroupName = $resourceGroupName
        $this.ResourceName = $resourceName
        $this.IsBaselineControl = $isBaselineControl
        $this.IsPreviewBaselineControl = $isPreviewBaselineControl
        $this.ControlSeverity = $controlSeverity
        $this.ResourceId = $resourceId
        $this.EffectiveResult = $effectiveResult
    }
}