Framework/Core/PolicySetup/PolicySetup.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
using namespace System.Management.Automation
using namespace Microsoft.Azure.Commands.Management.Storage.Models
using namespace Microsoft.WindowsAzure.Storage.Blob
using namespace Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel
Set-StrictMode -Version Latest

class PolicySetup: CommandBase
{
    [StorageHelper] $StorageAccountInstance;
    [AppInsightHelper] $AppInsightInstance;
    [string] $OrgName;
    [string] $DepartmentName;
    [string] $OrgFullName;

    hidden [string] $PolicyUrl;
    hidden [string] $InstallerUrl;
    hidden [string] $InstallerFileName;
    hidden [string] $Version = "2.1711.0";

    hidden [string] $ConfigContainerName = "policies";
    hidden [string] $InstallerContainerName = "installer";

    hidden [string] $FolderPath;
    hidden [string] $ConfigFolderPath;
    hidden [string] $InstallerFolderPath;
    hidden [string] $RunbookFolderPath;

    hidden [string] $InstallerFile;

    hidden [string] $IWRCommand;

    #PolicySetup([string] $subscriptionId, [InvocationInfo] $invocationContext, [string] $orgName, [string] $resourceGroupLocation):
    # Base($subscriptionId, $invocationContext)
    #{
    # $this.CreateInstance($subscriptionId, $orgName, "", $resourceGroupLocation);
    #}

    PolicySetup([string] $subscriptionId, [InvocationInfo] $invocationContext, [string] $orgName, [string] $departmentName, [string] $resourceGroupLocation, [string] $localPolicyFolderPath):
        Base($subscriptionId, $invocationContext)
    {
        $this.CreateInstance($subscriptionId, $orgName, $departmentName, $resourceGroupLocation, $localPolicyFolderPath);
    }

    [void] CreateInstance([string] $subscriptionId, [string] $orgName, [string] $departmentName, [string] $resourceGroupLocation, [string] $localPolicyFolderPath)
    {
        if([string]::IsNullOrWhiteSpace($orgName))
        {
            throw ([SuppressedException]::new(("The argument 'orgName' is null or empty"), [SuppressedExceptionType]::NullArgument))
        }
        $this.OrgName = $orgName;
        $this.DepartmentName = $departmentName;
        $this.OrgFullName = $orgName;

        if(-not [string]::IsNullOrWhiteSpace($departmentName))
        {
            $this.OrgFullName = $this.OrgFullName + "-" + $departmentName;
        }

        $prefix = [Constants]::AzSKModuleName + "-" + $this.OrgFullName;

        $candidateStorageAccountName = $prefix.Replace("-", "").ToLower() + "sa";
        [int] $availableLength = 24 - ([Constants]::AzSKModuleName.Length + 2)
        $storageRegEx = [regex]"^[a-z0-9]{3,24}$"
        if(-not $storageRegEx.IsMatch($candidateStorageAccountName))
        {
            throw ([SuppressedException]::new("Only alphanumeric characters are supported in OrgName and DeptName params. Total length (OrgName + DeptName) should be less than $availableLength characters ", [SuppressedExceptionType]::InvalidArgument))
        }

        $this.FolderPath = [System.Environment]::GetFolderPath("Desktop") + "\" + $prefix + "-Policy\";
        if(-not [string]::IsNullOrWhiteSpace($localPolicyFolderPath))
        {
            try
            {
                if (-not $localPolicyFolderPath.EndsWith("\"))
                {
                    $localPolicyFolderPath += "\";
                }

                $localPolicyFolderPath += $prefix + "-Policy\";

                if (-not (Test-Path $localPolicyFolderPath))
                {
                    mkdir -Path $localPolicyFolderPath -ErrorAction Stop | Out-Null
                }

                Copy-Item ($PSScriptRoot + "\README.txt") ($localPolicyFolderPath + "README.txt") -Force
                #Out-File -InputObject "AzSK folder check" -Force -FilePath $testFilePath -Encoding utf8
                #Remove-Item -Path $testFilePath -Force
                $this.FolderPath = $localPolicyFolderPath;
            }
            catch
            {
                throw ([SuppressedException]::new("Not able to access/modify the folder [$localPolicyFolderPath].`r`n$($_.ToString())", [SuppressedExceptionType]::InvalidOperation))
            }
        }

        $this.StorageAccountInstance = [StorageHelper]::new($subscriptionId, $prefix + "-RG" , $resourceGroupLocation, $prefix.Replace("-", "").ToLower() + "sa");
        $this.AppInsightInstance = [AppInsightHelper]::new($subscriptionId, $prefix + "-RG" , $resourceGroupLocation, $prefix + "-AppInsight");

        $this.ConfigFolderPath = $this.FolderPath + "Config\";
        $this.InstallerFolderPath = $this.FolderPath + "Installer\";
        $this.RunbookFolderPath = $this.FolderPath + "CA-Runbook\";
        
        $this.InstallerFileName = [Constants]::AzSKModuleName + "-EasyInstaller.ps1";
        $this.InstallerFile = $this.InstallerFolderPath + $this.InstallerFileName;

        # setup base version
        $azskConfig = [ConfigurationManager]::GetAzSKConfigData();
        if([Helpers]::CheckMember($azskConfig, "ConfigSchemaBaseVersion") -and (-not [string]::IsNullOrWhiteSpace($azskConfig.ConfigSchemaBaseVersion)))
        {
            $this.Version = $azskConfig.ConfigSchemaBaseVersion;
        }
    }

    [void] ModifyConfigs()
    {
        # Modify config files and save to temp location
        $metadataFileNames = @();

        if(-not [string]::IsNullOrWhiteSpace($this.InstallerUrl))
        {
            $this.IWRCommand = "iwr '$($this.InstallerUrl)' -UseBasicParsing | iex";
        }

        if((Get-ChildItem $this.ConfigFolderPath -Recurse -Force | Where-Object { $_.Name -eq "AzSK.json" } | Measure-Object).Count -eq 0)
        {
            $azskOverride = [ConfigOverride]::new("AzSK.json");
            $azskOverride.UpdatePropertyValue("PolicyMessage", "Running $([Constants]::AzSKModuleName) cmdlet using $($this.OrgFullName) policy...");
            if(-not [string]::IsNullOrWhiteSpace($this.IWRCommand))
            {
                $azskOverride.UpdatePropertyValue("InstallationCommand", $this.IWRCommand);
            }

            if($this.AppInsightInstance -and $this.AppInsightInstance.AppInsightInstance -and $this.AppInsightInstance.AppInsightInstance.Properties)
            {
                $azskOverride.UpdatePropertyValue("ControlTelemetryKey", $this.AppInsightInstance.AppInsightInstance.Properties.InstrumentationKey);
                $azskOverride.UpdatePropertyValue("EnableControlTelemetry", "true");
            }
            $azskOverride.WriteToFolder($this.ConfigFolderPath);
        }

        # Dynamically get list of files available in folder
        $metadataFileNames += Get-ChildItem $this.ConfigFolderPath -Recurse -Force |
                                Where-Object { $_.mode -match "-a---" -and $_.Name -ne "ServerConfigMetadata.json" } |
                                Select-Object -Property Name | Select-Object -ExpandProperty Name |
                                Select-Object @{ Label="Name"; Expression={ $_ } };

        $metadataOverride = [ConfigOverride]::new("ServerConfigMetadata.json");
        $metadataOverride.UpdatePropertyValue("OnlinePolicyList", $metadataFileNames);
        $metadataOverride.WriteToFolder($this.ConfigFolderPath);
    }

    [void] ModifyInstaller()
    {
        if(-not [string]::IsNullOrWhiteSpace($this.PolicyUrl))
        {
            # write SAS token url to installer file
            $folderName = [System.IO.Path]::GetDirectoryName($this.InstallerFile);

            # Check for environment specific installer file
            $fileName = $PSScriptRoot + "\" + [Constants]::AzSKModuleName +"-EasyInstaller.ps1";
            if(-not (Test-Path -Path $fileName))
            {
                $fileName = $PSScriptRoot + "\EasyInstaller.ps1";
            }
            $fileContent = Get-Content -Path $fileName;
            $fileContent = $fileContent.Replace("#PolicyUrl#", $this.PolicyUrl);
            $fileContent = $fileContent.Replace("#ModuleName#", [Constants]::AzSKModuleName);
            $fileContent = $fileContent.Replace("#OrgName#", $this.OrgFullName);

            if (-not (Test-Path $folderName))
            {
                mkdir -Path $folderName -ErrorAction Stop | Out-Null
            }

            if (-not $folderName.EndsWith("\"))
            {
                $folderName += "\";
            }

            Out-File -InputObject $fileContent -Force -FilePath $this.InstallerFile -Encoding utf8
            #Set-Content -Value $fileContent -Path $this.InstallerFile -Force
        }
        else
        {
            throw ([SuppressedException]::new("Not able to create installer file.", [SuppressedExceptionType]::Generic))
        }
    }

    [void] CopyRunbook()
    {
        # Quick fix: Temporary code added to make the policies run for non-CSE tenants. Suggested by Byna.
        try
        {
            if (-not (Test-Path $this.RunbookFolderPath))
            {
                mkdir -Path $this.RunbookFolderPath -ErrorAction Stop | Out-Null
            }
            
            if((Get-ChildItem $this.RunbookFolderPath -Force | Where-Object { $_.Name -eq "RunbookScanAgent.ps1" } | Measure-Object).Count -eq 0)
            {
                $caFilePath = (Get-Item -Path $PSScriptRoot).Parent.Parent.FullName + "\Configurations\ContinuousAssurance\RunbookScanAgent.ps1"
                Copy-Item ($caFilePath) ($this.RunbookFolderPath + "RunbookScanAgent.ps1")
            }

            $allCAFiles = @();
            $allCAFiles += Get-ChildItem $this.RunbookFolderPath -Force | Where-Object { $_.mode -match "-a---" }
            if($allCAFiles.Count -ne 0)
            {
                $this.StorageAccountInstance.UploadFilesToBlob($this.ConfigContainerName, "0.0.0", $allCAFiles);
            }
        }
        catch
        {
            $this.CommandError($_);
        }        
    }


    [MessageData[]] InstallPolicy()
    {
        $this.AppInsightInstance.CreateAppInsightIfNotExists();
        $container = $this.StorageAccountInstance.CreateStorageContainerIfNotExists($this.InstallerContainerName, [BlobContainerPublicAccessType]::Blob);
        if($container -and $container.CloudBlobContainer)
        {
            $this.InstallerUrl = $container.CloudBlobContainer.Uri.AbsoluteUri + "/" + $this.InstallerFileName;
        }
        $this.ModifyConfigs();

        $allFiles = @();
        $allFiles += Get-ChildItem $this.ConfigFolderPath -Recurse -Force | Where-Object { $_.mode -match "-a---" } #| Select-Object -Property FullName | Select-Object -ExpandProperty FullName;
        if($allFiles.Count -ne 0)
        {
            $this.StorageAccountInstance.UploadFilesToBlob($this.ConfigContainerName, $this.Version, $allFiles);
        }
        else
        {
            #throw ([SuppressedException]::new("No files found under folder [$($this.ConfigFolderPath)]", [SuppressedExceptionType]::InvalidOperation))
        }

        $container = $this.StorageAccountInstance.CreateStorageContainerIfNotExists($this.ConfigContainerName);
        if($container -and $container.CloudBlobContainer)
        {
            $this.PolicyUrl = $container.CloudBlobContainer.Uri.AbsoluteUri + "/```$(```$Version)/```$(```$FileName)" + $this.StorageAccountInstance.GenerateSASToken($this.ConfigContainerName);
        }
        $this.ModifyInstaller();

        $this.StorageAccountInstance.UploadFilesToBlob($this.InstallerContainerName, "", (Get-ChildItem -Path $this.InstallerFile));

        $this.CopyRunbook();

        $this.PublishCustomMessage(" `r`nThe setup has been completed and policies have been copied to [$($this.FolderPath)].`r`nRun the command below to install Organization specific version.`r`n$($this.IWRCommand)", [MessageType]::Update);
        $this.PublishCustomMessage(" `r`nNote: This is a basic setup and uses a public access blob for storing your org's installer. Once you have richer org policies, consider using a location/end-point protected by your tenant authentication.", [MessageType]::Warning);


        # Removing cleanup step
        #$this.CleanupTempFolders();
        return @();
    }

    [void] CleanupTempFolders()
    {
        Remove-Item -Path $this.ConfigFolderPath -Force -Recurse -ErrorAction Ignore
        Remove-Item -Path $this.InstallerFolderPath -Force -Recurse -ErrorAction Ignore
    }
}