Framework/Core/SVT/Services/DBForPostgreSQL.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
#using namespace Microsoft.Azure.Commands.AppService.Models
Set-StrictMode -Version Latest
class DBForPostgreSQL: AzSVTBase
{
    hidden [PSObject] $ResourceObject;
    hidden [PSObject] $PostgreSQLFirewallRules;
     
    DBForPostgreSQL([string] $subscriptionId, [SVTResource] $svtResource):
        Base($subscriptionId, $svtResource)
    {
          $this.GetResourceObject();
    }

    hidden [PSObject] GetResourceObject()
    {
      if (-not $this.ResourceObject) {
        $this.ResourceObject = Get-AzResource -ResourceId $this.ResourceId
        if(-not $this.ResourceObject)
        {
            throw ([SuppressedException]::new(("Resource '{0}' not found under Resource Group '{1}'" -f ($this.ResourceContext.ResourceName), ($this.ResourceContext.ResourceGroupName)), [SuppressedExceptionType]::InvalidOperation))
        }
      }

      return $this.ResourceObject;
    }    

    hidden [ControlResult] CheckPostgreSQLSSLConnection([ControlResult] $controlResult)
    {
      
      #Fetching ssl Object
      $ssl_option = $this.ResourceObject.properties.sslEnforcement
      #checking ssl is enabled or disabled
      if($ssl_option -eq 'Enabled')
      {
        $controlResult.AddMessage([VerificationResult]::Passed, "SSL enforcement is enabled");
      }
      else 
      {
        $controlResult.AddMessage([VerificationResult]::Failed, "SSL enforcement is disabled");
      }
      #return
      return $controlResult
    }

    [PSObject] GetFirewallRules()
    {
        if ($null -eq $this.PostgreSQLFirewallRules)
        {
             # List firewall rules for Azure Database for PostgreSQL
            $ResourceAppIdURI = [WebRequestHelper]::GetResourceManagerUrl()    
            $uri=[system.string]::Format($ResourceAppIdURI+"/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.DBforPostgreSQL/servers/{2}/firewallRules?api-version=2017-12-01",$this.SubscriptionContext.SubscriptionId,$this.ResourceContext.ResourceGroupName,$this.ResourceContext.ResourceName)
            try
            {
                $this.PostgreSQLFirewallRules = [WebRequestHelper]::InvokeGetWebRequest($uri);
            }
            catch
            {
                $this.PostgreSQLFirewallRules = 'error'
            }
        }
        return $this.PostgreSQLFirewallRules
    }

    hidden [ControlResult] CheckPostgreSQLFirewallIpRange([ControlResult] $controlResult)
    {
     
      $firewallRules = $this.GetFirewallRules()
      if ($firewallRules -eq 'error')
      {
        $controlResult.AddMessage([VerificationResult]::Manual, "Unable to get firewall rules for - [$($this.ResourceContext.ResourceName)]");
      }
      else
      {
        if([Helpers]::CheckMember($firewallRules,"id"))
        {
          $firewallRulesForAzure = $firewallRules | Where-Object { $_.name -ne "AllowAllWindowsAzureIps" }
          if(($firewallRulesForAzure | Measure-Object ).Count -eq 0)
          {
            $controlResult.AddMessage([VerificationResult]::Passed, "No custom firewall rules found.");
            return $controlResult
          }

          $controlResult.AddMessage([MessageData]::new("Current firewall settings for - ["+ $this.ResourceContext.ResourceName +"]",
                                                        $firewallRulesForAzure));

          $anyToAnyRule =  $firewallRulesForAzure | Where-Object { $_.properties.StartIpAddress -eq $this.ControlSettings.IPRangeStartIP -and $_.properties.EndIpAddress -eq  $this.ControlSettings.IPRangeEndIP}
          if (($anyToAnyRule | Measure-Object).Count -gt 0)
          {
              $controlResult.AddMessage([VerificationResult]::Failed,
                                          [MessageData]::new("Firewall rule covering all IPs (Start IP address: $($this.ControlSettings.IPRangeStartIP) To End IP Address: $($this.ControlSettings.IPRangeEndIP)) is defined."));
          }
          else
          {
              $controlResult.VerificationResult = [VerificationResult]::Verify
          }
          $controlResult.SetStateData("Firewall IP addresses", $firewallRules);
        }
        else
        {
          $controlResult.AddMessage([VerificationResult]::Passed, "No custom firewall rules found.");  
        }
          
      }

      return $controlResult;
    }

    hidden [ControlResult] CheckPostgreSQLFirewallAccessAzureService([ControlResult] $controlResult)
    {
        $firewallRules = $this.GetFirewallRules()
        if ($firewallRules -eq 'error')
        {
          $controlResult.AddMessage([VerificationResult]::Manual, "Unable to get firewall rules for - [$($this.ResourceContext.ResourceName)]");
        }
        else
        {
          if([Helpers]::CheckMember($firewallRules, "id"))
          {
            $firewallRulesForAzure = $firewallRules | Where-Object { $_.name -eq "AllowAllWindowsAzureIps" }
            if(($firewallRulesForAzure | Measure-Object ).Count -gt 0)
            {
              $controlResult.AddMessage([VerificationResult]::Verify,
                                          [MessageData]::new("'Allow access to Azure services' is turned ON."));
            }    
            else
            {
              $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("'Allow access to Azure services' is turned OFF."));
            }
          }
          else
          {
            $controlResult.AddMessage([VerificationResult]::Passed, "No custom firewall rules found.");
          }   
        }
      return $controlResult
    }

    # This is a verify control. As the backup is by default enabled, the customer must verify backup settings from a BC-DR standpoint.
    hidden [ControlResult] CheckPostgreSQLBCDRStatus([ControlResult] $controlResult)
    {
      $backupSettings = @{ 
                            "backupRetentionDays" = $this.ResourceObject.properties.storageProfile.backupRetentionDays;
                            "geoRedundantBackup" =  $this.ResourceObject.properties.storageProfile.geoRedundantBackup
                         }

      $controlResult.AddMessage([VerificationResult]::Verify, "Verify back up settings for PostgreSQL server.",$backupSettings);
      $controlResult.SetStateData("Backup setting:", $backupSettings);

      return $controlResult;
    }

    hidden [ControlResult] CheckPostgreSQLATPSetting([ControlResult] $controlResult)
    {
      $securityAlertPolicies = ""
      # Get advanced threat protection settings for Azure Database of PostgreSQL
      $ResourceAppIdURI = [WebRequestHelper]::GetResourceManagerUrl()    
      $uri=[system.string]::Format($ResourceAppIdURI+"/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.DBforPostgreSQL/servers/{2}/securityAlertPolicies/Default?api-version=2017-12-01",$this.SubscriptionContext.SubscriptionId,$this.ResourceContext.ResourceGroupName,$this.ResourceContext.ResourceName)

      try
      {
        $securityAlertPolicies = [WebRequestHelper]::InvokeGetWebRequest($uri);
      }
      catch
      {
        $controlResult.AddMessage([VerificationResult]::Manual, "Unable to get Advanced Threat Protection setting for - [$($this.ResourceContext.ResourceName)]");
      }
      if([Helpers]::CheckMember($securityAlertPolicies,"properties.state") -and [Helpers]::CheckMember($securityAlertPolicies.properties,"emailAccountAdmins", $false))
      {
        if(($securityAlertPolicies.properties.state -eq 'Enabled') -and ($securityAlertPolicies.properties.emailAccountAdmins -eq 'true')) 
        {
          $controlResult.AddMessage([VerificationResult]::Passed, "Advanced Threat Protection is enabled.");
        }
        else
        {
          $result = @{ 'securityAlertPolicies' = @{'State' = $securityAlertPolicies.properties.state; 'emailAccountAdmins' = $securityAlertPolicies.properties.emailAccountAdmins }}
          $controlResult.AddMessage([VerificationResult]::Failed, "Advanced Threat Protection is disabled.", $result);
          $controlResult.SetStateData("Advanced Threat Protection setting:", $result);
        }
      }
      else
      {
        $controlResult.AddMessage([VerificationResult]::Manual, "Unable to get Advanced Threat Protection setting for - [$($this.ResourceContext.ResourceName)]");
      }
      return $controlResult;
    }

    hidden [ControlResult] CheckPostgreSQLVnetRules([ControlResult] $controlResult)
    {
      $virtualNetworkRules = ''
      # Get virtual network rules for Azure Database of PostgreSQL
      $ResourceAppIdURI = [WebRequestHelper]::GetResourceManagerUrl()    
      $uri=[system.string]::Format($ResourceAppIdURI+"/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.DBforPostgreSQL/servers/{2}/virtualNetworkRules?api-version=2017-12-01",$this.SubscriptionContext.SubscriptionId,$this.ResourceContext.ResourceGroupName,$this.ResourceContext.ResourceName)      

      try
      {
        $virtualNetworkRules = [WebRequestHelper]::InvokeGetWebRequest($uri);
      }
      catch
      {
        $controlResult.AddMessage([VerificationResult]::Manual, "Unable to fetch details of functions.");
      }
      if ([Helpers]::CheckMember($virtualNetworkRules,"id")) {
            
        $vnetRules = $virtualNetworkRules | ForEach-Object {
            @{ 'name'="$($_.name)"; 'id'="$($_.id)"; 'virtualNetworkSubnetId'="$($_.properties.virtualNetworkSubnetId)" }
        }
        $controlResult.AddMessage([VerificationResult]::Passed, "The enabled virtual network rules are:",$vnetRules);
      }
      else
      {
          $controlResult.AddMessage([VerificationResult]::Verify, "There are no virtual network rules enabled for '$($this.ResourceContext.ResourceName)' server. Consider using virtual network rules for improved isolation.");
      }
      
      return $controlResult
    }

    # This function checks for a specific category of log.
    # We have created this custom function since log category based filter is not available in the default 'CheckDiagnosticsSettings' function.
    hidden [ControlResult] CheckPostgreSQLDiagnosticsSettings([ControlResult] $controlResult) {
      $diagnostics = $Null
      try
      {
        $diagnostics = Get-AzDiagnosticSetting -ResourceId $this.ResourceId -ErrorAction Stop -WarningAction SilentlyContinue
      }
      catch
      {
        if([Helpers]::CheckMember($_.Exception, "Response") -and ($_.Exception).Response.StatusCode -eq [System.Net.HttpStatusCode]::NotFound)
        {
          $controlResult.AddMessage([VerificationResult]::Failed, "Diagnostics setting is disabled for resource - [$($this.ResourceContext.ResourceName)].");
          return $controlResult
        }
        else
        {
          $this.PublishException($_);
        }
      }
      if($Null -ne $diagnostics -and ($diagnostics.Logs | Measure-Object).Count -ne 0)
      {
        $nonCompliantLogs = $diagnostics.Logs | Where-Object {$_.Category -eq 'PostgreSQLLogs'} |
                  Where-Object { -not ($_.Enabled -and
                        ($_.RetentionPolicy.Days -eq $this.ControlSettings.Diagnostics_RetentionPeriod_Forever -or
                        $_.RetentionPolicy.Days -ge $this.ControlSettings.Diagnostics_RetentionPeriod_Min))};

        $selectedDiagnosticsProps = $diagnostics | Select-Object -Property @{ Name = "Logs"; Expression = {$_.Logs |  Where-Object {$_.Category -eq 'PostgreSQLLogs'}}}, StorageAccountId, EventHubName, Name;

        if(($nonCompliantLogs | Measure-Object).Count -eq 0)
        {
          $controlResult.AddMessage([VerificationResult]::Passed,
            "Diagnostics settings are correctly configured for resource - [$($this.ResourceContext.ResourceName)]",
            $selectedDiagnosticsProps);
        }
        else
        {
          $failStateDiagnostics = $nonCompliantLogs | Select-Object -Property @{ Name = "Logs"; Expression = {$_.Logs |  Where-Object {$_.Category -eq 'PostgreSQLLogs'}}}, StorageAccountId, EventHubName, Name;
          $controlResult.SetStateData("Non compliant resources are:", $failStateDiagnostics);
          $controlResult.AddMessage([VerificationResult]::Failed,
            "Diagnostics settings are either disabled OR not retaining logs for at least $($this.ControlSettings.Diagnostics_RetentionPeriod_Min) days for resource - [$($this.ResourceContext.ResourceName)]",
            $selectedDiagnosticsProps);
        }
      }
      else
      {
        $controlResult.AddMessage([VerificationResult]::Failed, "Diagnostics setting is disabled for resource - [$($this.ResourceContext.ResourceName)].");
      }
      return $controlResult
    }

    hidden [ControlResult] CheckPostgreSQLConnectionThrottlingServerParameter([ControlResult] $controlResult) {
        $status = '';
        $status = $this.CheckServerParameters("connection_throttling")
        if ($status -eq "ON")
        { 
            $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("Connection throttling for $($this.ResourceContext.ResourceName) is turned ON."));
        }
        elseif ($status -eq "OFF")
        {
            $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Connection throttling for $($this.ResourceContext.ResourceName) is turned OFF."));
        }
        else
        {
            $controlResult.AddMessage([VerificationResult]::Manual, [MessageData]::new("Unable to validate control. Please verify from portal, 'connection-throttling' is ON or OFF."));
        }
        return $controlResult
    }

    hidden [string] CheckServerParameters([string] $parameterName)
    {
        $status = '';
        # Get postgreSQL server parameter
        $ResourceAppIdURI = [WebRequestHelper]::GetResourceManagerUrl()
        $uri = [system.string]::Format($ResourceAppIdURI + "subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.DBforPostgreSQL/servers/{2}/configurations/{3}?api-version=2017-12-01", $this.SubscriptionContext.SubscriptionId, $this.ResourceContext.ResourceGroupName, $this.ResourceContext.ResourceName, $parameterName)
        $response = $null;
        try
        {     
          $response = [WebRequestHelper]::InvokeGetWebRequest($uri);
        } 
        catch
        { 
          $response = $null;
        }        
        if (($null -ne $response) -and (($response | Measure-Object).Count -gt 0))
        {
          if (([Helpers]::CheckMember($response[0], "properties.value")) -and ($response.properties.value -eq "ON")) {
              $status = 'ON'
          }
          else {
              $status = 'OFF'
          }
        }
        else {
          $status = 'error'
        }
        return $status
    }

    hidden [ControlResult] CheckPostgreSQLLoggingParameters([ControlResult] $controlResult) {
        $statusLogConnections = '';
        $statusLogDisconnections = '';
        $statusLogConnections = $this.CheckServerParameters("log_connections")
        $statusLogDisconnections = $this.CheckServerParameters("log_disconnections")
        $message = "'log_connections' for $($this.ResourceContext.ResourceName) is turned " + $statusLogConnections + "." 
        $message += "`n'log_disconnections' for $($this.ResourceContext.ResourceName) is turned " + $statusLogDisconnections + "."
        if (($statusLogConnections -eq "ON") -and ($statusLogDisconnections -eq "ON"))
        { 
          $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new($message));
        }
        elseif (($statusLogConnections -eq "OFF") -or ($statusLogDisconnections -eq "OFF"))
        {
          $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new($message));
          $controlResult.SetStateData("Log server parameters", @{ 'log_connections' = $statusLogConnections; "log_disconnections" = $statusLogDisconnections});
        }
        else
        {
          $controlResult.AddMessage([VerificationResult]::Manual, [MessageData]::new("Unable to validate control.Please verify from portal values for log_connections and log_disconnections."));
        }
        return $controlResult
    }

}