Framework/Managers/ControlBaselineManager.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
Set-StrictMode -Version Latest

class ControlBaselineManager
{
    hidden [PSObject] $AzSKResourceGroup = $null;
    hidden [PSObject] $AzSKStorageAccount = $null;
    hidden [PSObject] $AzSKStorageResourceBaselineContainer = $null;
    hidden [int] $HasWritePermissions = -1;
    hidden [string]    $BaselineResourceBlobName = "BaselineResourceBlob.json"
    hidden [string] $CAScanProgressSnapshotsContainerName = [Constants]::CAScanProgressSnapshotsContainerName
    hidden [BaselineResourceMap] $BaselineControlObj = $null
    [PSObject] $ControlSettings;
    hidden [ActiveStatus] $ActiveStatus = [ActiveStatus]::NotStarted;

    hidden static [ControlBaselineManager] $Instance = $null;
    static [ControlBaselineManager] GetInstance()
    {
        if ( $null -eq  [ControlBaselineManager]::Instance)
        {
            [ControlBaselineManager]::Instance = [ControlBaselineManager]::new();
        }
        return [ControlBaselineManager]::Instance
    }

    ControlBaselineManager()
    {
        $this.ControlSettings = [ConfigurationManager]::LoadServerConfigFile("ControlSettings.json");
        #$this.GetAzSKControlBaselineContainer()
    }

    hidden [bool] HasControlBaselineStatusWritePermissions()
    {
        $hasPermissions = $false;
        return $hasPermissions;
    }

    hidden [void] GetAzSKControlBaselineContainer()
    {
        if($null -eq $this.AzSKStorageAccount)
        {
            $this.GetAzSKStorageAccount()
        }
        if($null -eq $this.AzSKStorageAccount)
        {
            return;
        }


        try
        {
            #Able to read the container then read permissions are good
            $containerObject = Get-AzureStorageContainer -Context $this.AzSKStorageAccount.Context -Name $this.CAScanProgressSnapshotsContainerName -ErrorAction Stop
            $this.AzSKStorageResourceBaselineContainer = $containerObject;
        }
        catch
        {
            try
            {
                New-AzureStorageContainer -Context $this.AzSKStorageAccount.Context -Name $this.CAScanProgressSnapshotsContainerName -ErrorAction SilentlyContinue
                $containerObject = Get-AzureStorageContainer -Context $this.AzSKStorageAccount.Context -Name $this.CAScanProgressSnapshotsContainerName -ErrorAction SilentlyContinue
                $this.AzSKStorageResourceBaselineContainer = $containerObject;
            }
            catch
            {
                #Do nothing
            }
        }
    }

    hidden [void] GetAzSKStorageAccount()
    {
        if($null -eq $this.AzSKResourceGroup)
        {
            $this.GetAzSKRG();
        }
        if($null -ne $this.AzSKResourceGroup)
        {
            $StorageAccount = Get-AzureRmStorageAccount -ResourceGroupName $this.AzSKResourceGroup.ResourceGroupName | Where-Object {$_.StorageAccountName -like 'azsk*'} -ErrorAction SilentlyContinue
            #if no storage account found then it assumes that there is no control state feature is not used and if there are more than one storage account found it assumes the same
            $this.AzSKStorageAccount = $StorageAccount;
        }
    }

    hidden [PSObject] GetAzSKRG()
    {
        $azSKConfigData = [ConfigurationManager]::GetAzSKConfigData()
        $resourceGroup = Get-AzureRmResourceGroup -Name $azSKConfigData.AzSKRGName -ErrorAction SilentlyContinue
        $this.AzSKResourceGroup = $resourceGroup
        return $resourceGroup;
    }


    [void] UpdateResourceStatus([string] $resourceId, [ScanState] $state)
    {
        $resourceValues = @();
        $this.GetBaselineControlObject();
        if($this.IsListAvailableAndActive())
        {
            #$idHash = [Helpers]::ComputeHash($resourceId)
            $resourceValue = $this.BaselineControlObj.ResourceMapTable | Where-Object { $_.Id -eq $resourceId};
            if($null -ne $resourceValue)
            {
                $resourceValue.ModifiedDate = [DateTime]::UtcNow;
                $resourceValue.State = $state;
                #$this.BaselineControlObj.ResourceMapTable[$idHash] = $resourceValue;
            }
            else
            {
                $resourceValue = [BaselineResource]@{
                    Id = $resourceId;
                    State = $state;
                    CreatedDate = [DateTime]::UtcNow;
                    ModifiedDate = [DateTime]::UtcNow;
                }
                $this.BaselineControlObj.ResourceMapTable +=$resourceValue;
            }

            $this.PersistStorageBlob();
        }
    }

    [void] RemoveControlBaseline()
    {
        if($null -ne $this.BaselineControlObj)
        {
            $AzSKTemp = [Constants]::AzSKAppFolderPath + "\TempState";
            if(-not (Test-Path "$AzSKTemp\ControlsBaseline"))
            {
                mkdir -Path "$AzSKTemp\ControlsBaseline" -ErrorAction Stop | Out-Null
            }
            $masterFilePath = "$AzSKTemp\ControlsBaseline\$($this.BaselineResourceBlobName)"
            $controlStateBlob = Get-AzureStorageBlob -Container $this.CAScanProgressSnapshotsContainerName -Context $this.AzSKStorageAccount.Context -Blob "$($this.BaselineResourceBlobName)" -ErrorAction SilentlyContinue

            if($null -ne $controlStateBlob)
            {
                Get-AzureStorageBlobContent -CloudBlob $controlStateBlob.ICloudBlob -Context $this.AzSKStorageAccount.Context -Destination $masterFilePath -Force                
                $baselineResources  = Get-ChildItem -Path $masterFilePath -Force | Get-Content | ConvertFrom-Json
                if($baselineResources -ne $null -and ($baselineResources.ResourceMapTable | Measure-Object).Count -gt 0 -and ($baselineResources.ResourceMapTable | Where-Object { $_.State -ne "COMP" } | Measure-Object).Count -eq 0)
                {
                    $this.ArchiveBlob("_End_");
                    Remove-AzureStorageBlob -CloudBlob $controlStateBlob.ICloudBlob -Force -Context $this.AzSKStorageAccount.Context 
                }
                
            }            
            $this.BaselineControlObj = $null
        }
    }

    [void] CreateResourceMasterList([PSObject] $resourceIds)
    {

        if(($resourceIds | Measure-Object).Count -gt 0)
        {
            $resourceIdMap = @();
            $resourceIds | ForEach-Object {
                $resourceId = $_;
                #$hashId = [Helpers]::ComputeHash($resourceId);
                $resourceValue = [BaselineResource]@{
                    Id = $resourceId;
                    State = [ScanState]::INIT
                    CreatedDate = [DateTime]::UtcNow;
                    ModifiedDate = [DateTime]::UtcNow;
                }
                #$resourceIdMap.Add($hashId,$resourceValue);
                $resourceIdMap +=$resourceValue
            }
            $masterControlBlob = [BaselineResourceMap]@{
                Id = [DateTime]::UtcNow.ToString("yyyyMMdd_HHmmss");
                CreatedDate = [DateTime]::UtcNow;
                ResourceMapTable = $resourceIdMap;
            }
            $this.BaselineControlObj = $masterControlBlob;
            $this.PersistStorageBlob();
            $this.ActiveStatus = [ActiveStatus]::Yes;
        }
    }

    [void] PersistStorageBlob()
    {
        $this.GetBaselineControlObject();
        if($null -ne $this.BaselineControlObj)
        {
            $AzSKTemp = [Constants]::AzSKAppFolderPath + "\TempState";
            if(-not (Test-Path "$AzSKTemp\ControlsBaseline"))
            {
                mkdir -Path "$AzSKTemp\ControlsBaseline" -ErrorAction Stop | Out-Null
            }
            $masterFilePath = "$AzSKTemp\ControlsBaseline\$($this.BaselineResourceBlobName)"

            [Helpers]::ConvertToJsonCustom($this.BaselineControlObj) | Out-File $masterFilePath -Force
            Set-AzureStorageBlobContent -File $masterFilePath -Container $this.CAScanProgressSnapshotsContainerName -BlobType Block -Context $this.AzSKStorageAccount.Context -Force
        }
    }

    hidden [void] ArchiveBlob()
    {
        $this.ArchiveBlob("_");
    }

    hidden [void] ArchiveBlob([string] $token)
    {
        try
        {
            $AzSKTemp = [Constants]::AzSKAppFolderPath + "\TempState";
            
            if(-not (Test-Path "$AzSKTemp\ControlsBaseline"))
            {
                mkdir -Path "$AzSKTemp\ControlsBaseline" -ErrorAction Stop | Out-Null
            }
            $archiveName =  $this.CAScanProgressSnapshotsContainerName + $token +  (Get-Date).ToUniversalTime().ToString("yyyyMMddHHmmss") + ".json";
            $masterFilePath = "$AzSKTemp\ControlsBaseline\$archiveName"
            $controlStateBlob = Get-AzureStorageBlob -Container $this.CAScanProgressSnapshotsContainerName -Context $this.AzSKStorageAccount.Context -Blob "$($this.BaselineResourceBlobName)" -ErrorAction SilentlyContinue
            if($null -ne $controlStateBlob)
            {
                Get-AzureStorageBlobContent -CloudBlob $controlStateBlob.ICloudBlob -Context $this.AzSKStorageAccount.Context -Destination $masterFilePath -Force            
                Set-AzureStorageBlobContent -File $masterFilePath -Container $this.CAScanProgressSnapshotsContainerName -Blob "Archive/$archiveName" -BlobType Block -Context $this.AzSKStorageAccount.Context -Force
            }
        }
        catch
        {
            #eat exception as archive should not impact actual flow
        }
    }

    hidden [void] GetBaselineControlObject()
    {
        if($null -eq $this.BaselineControlObj)
        {
            # region Migration
            # AzSK TBR
            #[MigrationHelper]::TryMigration($this.SubscriptionContext, $this.InvocationContext);
            #endregion

            $AzSKTemp = [Constants]::AzSKAppFolderPath + "\TempState";
            if(-not (Test-Path "$AzSKTemp\ControlsBaseline"))
            {
                mkdir -Path "$AzSKTemp\ControlsBaseline" -ErrorAction Stop | Out-Null
            }
            $masterFilePath = "$AzSKTemp\ControlsBaseline\$($this.BaselineResourceBlobName)"
            $controlStateBlob = Get-AzureStorageBlob -Container $this.CAScanProgressSnapshotsContainerName -Context $this.AzSKStorageAccount.Context -Blob "$($this.BaselineResourceBlobName)" -ErrorAction SilentlyContinue

            if($null -ne $controlStateBlob)
            {
                Get-AzureStorageBlobContent -CloudBlob $controlStateBlob.ICloudBlob -Context $this.AzSKStorageAccount.Context -Destination $masterFilePath -Force
                $this.BaselineControlObj = Get-ChildItem -Path $masterFilePath -Force | Get-Content | ConvertFrom-Json
            }
        }
    }

    [ActiveStatus] IsMasterListActive()
    {
        if($null -eq $this.AzSKStorageAccount -or $null -eq $this.AzSKStorageResourceBaselineContainer  )
        {
         $this.GetAzSKControlBaselineContainer();
        }
        if($null -ne $this.ControlSettings.BaselineControls)
        {
            $this.GetBaselineControlObject();
            $expiryInDays = [Int32]::Parse($this.ControlSettings.BaselineControls.ExpiryInDays);
            if($null -eq $this.BaselineControlObj)
            {
                return $this.ActiveStatus = [ActiveStatus]::No;
            }
            if($this.BaselineControlObj.CreatedDate.AddDays($expiryInDays) -lt [DateTime]::UtcNow)
            {
                $this.RemoveControlBaseline();
                return $this.ActiveStatus = [ActiveStatus]::No;

            }
            return $this.ActiveStatus = [ActiveStatus]::Yes

        }
        else
        {
            return $this.ActiveStatus = [ActiveStatus]::No;

        }
    }

    [PSObject] GetResourceStatus([string] $resourceId)
    {
        $resourceValues = @();
        $this.GetBaselineControlObject();
        if($this.IsListAvailableAndActive())
        {
            $idHash = [Helpers]::ComputeHash($resourceId)
            $resourceValue = $this.BaselineControlObj.ResourceMapTable[$idHash];
            $resourceValues += $resourceValue;
            return $resourceValues;
        }
        return $null;
    }

    [PSObject] GetNonScannedResources()
    {
        $nonScannedResources = @();
        $this.GetBaselineControlObject();
        if($this.IsListAvailableAndActive())
        {
            $nonScannedResources +=[BaselineResource[]] $this.BaselineControlObj.ResourceMapTable | Where-Object {$_.State -eq [ScanState]::INIT}
            return $nonScannedResources;
        }
        return $null;
    }

    [PSObject] GetAllListedResources()
    {
        $nonScannedResources = @();
        $this.ArchiveBlob()
        $this.GetBaselineControlObject();
        if($this.IsListAvailableAndActive())
        {
            $nonScannedResources += $this.BaselineControlObj.ResourceMapTable
            return $nonScannedResources;
        }
        return $null;
    }

    [Bool] IsListAvailableAndActive()
    {
        if($null -ne $this.BaselineControlObj -and $this.ActiveStatus -eq [ActiveStatus]::Yes -and $null -ne $this.BaselineControlObj.ResourceMapTable)
        {
            return $true
        }
        else
        {
            return $false
        }
    }

    [PSObject] GetBaselineControlDetails()
    {
        return  $this.ControlSettings.BaselineControls
    }
}