Framework/Listeners/CA/WriteCAStatus.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
Set-StrictMode -Version Latest 
#Listner to write CA scan status on completion of resource scan
class WriteCAStatus: ListenerBase
{
    hidden static [WriteCAStatus] $Instance = $null;
    static [WriteCAStatus] GetInstance()
    {
        if ( $null -eq  [WriteCAStatus]::Instance)
        {
            [WriteCAStatus]::Instance = [WriteCAStatus]::new();
        }    
        return [WriteCAStatus]::Instance
    }


    [void] RegisterEvents()
    {
        $this.UnregisterEvents();       

        $this.RegisterEvent([AzSKRootEvent]::GenerateRunIdentifier, {
            $currentInstance = [WriteCAStatus]::GetInstance();
            try 
            {
                $currentInstance.SetRunIdentifier([AzSKRootEventArgument] ($Event.SourceArgs | Select-Object -First 1));                         
            }
            catch 
            {
                $currentInstance.PublishException($_);
            }
        });

        $this.RegisterEvent([SVTEvent]::EvaluationCompleted, {
            $currentInstance = [WriteCAStatus]::GetInstance();
            try 
            {
                $props = $Event.SourceArgs[0];
                if($props)
                {
                    if($props.IsResource())
                    {
                        #Update resource scan completion in CA storage account
                        $scanSource = [AzSKSettings]::GetInstance().GetScanSource();
                        [PartialScanManager] $partialScanMngr = [PartialScanManager]::GetInstance();
                        $baselineControlsDetails = $partialScanMngr.GetBaselineControlDetails()
                        #If Scan source is in supported sources or UsePartialCommits switch is available
                        if ($currentInstance.InvocationContext.BoundParameters["UsePartialCommits"] -or ($baselineControlsDetails.SupportedSources -contains $scanSource))
                        {
                            $partialScanMngr.UpdateResourceStatus( $props.ResourceContext.ResourceId,"COMP");
                        }
                    }                    
                }            
            }
            catch 
            {
                $currentInstance.PublishException($_);
            }
        });

        $this.RegisterEvent([SVTEvent]::CommandStarted, {
           $currentInstance = [WriteCAStatus]::GetInstance();
           try
           {
                $props = $Event.SourceArgs[0];
                $version = $currentInstance.InvocationContext.MyCommand.Version
                if($null -ne $props)
                {
                    $scanSource = [RemoteReportHelper]::GetScanSource();
                    if($scanSource -ne [ScanSource]::Runbook) { return; }                                                                        
                    [ComplianceStateTableEntity[]] $ResourceFlatEntries = @();
                    $complianceReportHelper = [ComplianceReportHelper]::new($props.SubscriptionContext, $version); 
                    $complianceData = $null;
                    if($complianceReportHelper.HaveRequiredPermissions())
                    {
                        $selectColumns = @("PartitionKey","RowKey");
                        $complianceData = $complianceReportHelper.GetSubscriptionComplianceReport($null, $selectColumns);
                    }
                    if(($complianceData | Measure-Object).Count -gt 0)
                    {
                        $resourceHashMap = @{};
                        [ResourceInventory]::FetchResources();   
                        [ResourceInventory]::FilteredResources | ForEach-Object{
                            $resource = $_;
                            $resourceIdHash = [Helpers]::ComputeHash($resource.ResourceId.ToLower());
                            if($null -eq $resourceHashMap[$resourceIdHash])
                            {
                                $resourceHashMap.Add($resourceIdHash, $resource)
                            }                        
                        }
                        $subHash = [Helpers]::ComputeHash($props.SubscriptionContext.Scope.ToLower());
                        if($null -eq $resourceHashMap[$subHash])
                        {
                            $resourceHashMap.Add($subHash,$props.SubscriptionContext.Scope);
                        }
                        [string[]] $deletedResources = @();
                    
                        foreach($resourceRecord in $complianceData)
                        {
                            if($null -eq $resourceHashMap[$resourceRecord.PartitionKey] -and -not $deletedResources.Contains($resourceRecord.PartitionKey))
                            {                                
                                $deletedResources += $resourceRecord.PartitionKey;
                            }
                        }
                        if(($deletedResources | Measure-Object).Count -gt 0)
                        {
                            $recordsToBeDeleted = $complianceReportHelper.GetSubscriptionComplianceReport($deletedResources);
                            if(($recordsToBeDeleted | Measure-Object).Count -gt 0)
                            {
                                $recordsToBeDeleted | ForEach-Object { $_.IsActive = $false;}
                            }
                            $complianceReportHelper.SetLocalSubscriptionScanReport($recordsToBeDeleted);
                        }
                    }                    
                }               
           }
           catch
           {
               $currentInstance.PublishException($_);
           }
       });

         $this.RegisterEvent([SVTEvent]::CommandCompleted, {
            $currentInstance = [PartialScanManager]::GetInstance();
            try 
            {
                $currentInstance = [WriteCAStatus]::GetInstance();
                $scanSource = [AzSKSettings]::GetInstance().GetScanSource();
                [PartialScanManager] $partialScanMngr = [PartialScanManager]::GetInstance();
                $baselineControlsDetails = $partialScanMngr.GetBaselineControlDetails()
                #If Scan source is in supported sources or UsePartialCommits switch is available
                if ($currentInstance.InvocationContext.BoundParameters["UsePartialCommits"] -or ($baselineControlsDetails.SupportedSources -contains $scanSource))
                {
                    $partialScanMngr.RemovePartialScanData();   
                }
            }
            catch 
            {
                $currentInstance.PublishException($_);
            }
        });

        $this.RegisterEvent([AzSKRootEvent]::PublishCustomData, {
            $currentInstance = [WriteCAStatus]::GetInstance();
            try
            {    
                $CustomDataObj =  $Event.SourceArgs
                $CustomObjectData=$CustomDataObj| Select-Object -exp Messages| Select-Object -exp DataObject

                if($CustomObjectData.Name -eq "PolicyComplianceTelemetry")
                {        
                    try {
                        $subId = $CustomObjectData.Value;
                        $policyCompliance = Get-AzureRmPolicyState -SubscriptionId $subId | Select-Object ResourceId,PolicyDefinitionId,PolicyAssignmentName,IsCompliant,PolicyAssignmentScope
                        [RemoteApiHelper]::PostPolicyComplianceTelemetry($policyCompliance);    
                    }
                    catch {
                        $currentInstance.PublishException($_);
                    }                                
                }   
                else
                {
                    $ResourceControlsData = $CustomObjectData.Value;
                    if($null -ne $ResourceControlsData.ResourceContext -and ($ResourceControlsData.Controls | Measure-Object).Count -gt 0)
                    {
                        $ResourceControlsDataMini = "" | Select-Object ResourceName, ResourceGroupName, ResourceId, Controls, ChildResourceNames
                        $ResourceControlsDataMini.ResourceName = $ResourceControlsData.ResourceContext.ResourceName;
                        $ResourceControlsDataMini.ResourceGroupName = $ResourceControlsData.ResourceContext.ResourceGroupName;
                        $ResourceControlsDataMini.ResourceId = $ResourceControlsData.ResourceContext.ResourceId;
                        $ResourceControlsDataMini.ChildResourceNames = $ResourceControlsData.ChildResourceNames;
                        $controls = @();
                        $ResourceControlsData.Controls | ForEach-Object {
                            $control = "" | Select-Object ControlStringId, ControlId;
                            $control.ControlStringId = $_.ControlId;
                            $control.ControlId = $_.Id;
                            $controls += $control;
                        }
                        $ResourceControlsDataMini.Controls = $controls;            

                        #compute hash for the given resource
                        $props = $Event.SourceArgs[0];
                        $version = $currentInstance.InvocationContext.MyCommand.Version

                        if($null -ne $props)
                        {
                            [string[]] $partitionKeys = @();       
                            [ComplianceStateTableEntity[]] $RecordsToBeDeleted = @();         
                            $partitionKey = [Helpers]::ComputeHash($ResourceControlsDataMini.ResourceId.ToLower());                
                            $partitionKeys += $partitionKey
                            $complianceReportHelper = [ComplianceReportHelper]::new($props.SubscriptionContext, $version); 

                            $ComplianceStateData = $null;

                            if($complianceReportHelper.HaveRequiredPermissions())
                            {
                                $ComplianceStateData = $complianceReportHelper.GetSubscriptionComplianceReport($partitionKeys); 
                            }
                            
                            if(($ComplianceStateData | Measure-Object).Count -gt 0)
                            {
                                $ComplianceStateData | ForEach-Object {
                                    $row = $_;
                                    if(($ResourceControlsDataMini.Controls | Where-Object { $_.ControlId -eq $row.ControlIntId} | Measure-Object).Count -gt 0)
                                    {
                                        if(-not [string]::IsNullOrWhiteSpace($row.ChildResourceName))
                                        {
                                            if(($ResourceControlsDataMini.ChildResourceNames | Where-Object {$_ -eq $row.ChildResourceName} | Measure-Object).Count -le 0)
                                            {
                                                $row.IsActive = $false;
                                                $RecordsToBeDeleted += $row;
                                            }
                                        }                            
                                    }
                                    else {
                                        $row.IsActive = $false;
                                        $RecordsToBeDeleted += $row;
                                    }
                                }
                                if(($RecordsToBeDeleted | Measure-Object).Count -gt 0)
                                {
                                    $complianceReportHelper.SetLocalSubscriptionScanReport($RecordsToBeDeleted);
                                }
                            }
                        }
                    }
                    
                }
            }
            catch
            {
                $currentInstance.PublishException($_);
            }
        });
    }


}