Framework/Core/SVT/Services/KubernetesService.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
Set-StrictMode -Version Latest 
class KubernetesService: AzSVTBase
{
    hidden [PSObject] $ResourceObject;

    KubernetesService([string] $subscriptionId, [SVTResource] $svtResource): 
        Base($subscriptionId, $svtResource) 
    { 
        $this.GetResourceObject();
    }

    hidden [PSObject] GetResourceObject()
    {
        if (-not $this.ResourceObject) 
        {
            $ResourceAppIdURI = [WebRequestHelper]::GetResourceManagerUrl();
            $AccessToken = [ContextHelper]::GetAccessToken($ResourceAppIdURI)
            if($null -ne $AccessToken)
            {

                $header = "Bearer " + $AccessToken
                $headers = @{"Authorization"=$header;"Content-Type"="application/json";}

                $uri=[system.string]::Format("{0}subscriptions/{1}/resourceGroups/{2}/providers/Microsoft.ContainerService/managedClusters/{3}?api-version=2018-03-31",$ResourceAppIdURI,$this.SubscriptionContext.SubscriptionId, $this.ResourceContext.ResourceGroupName, $this.ResourceContext.ResourceName)
                $result = ""
                $err = $null
                try {
                    $propertiesToReplace = @{}
                    $propertiesToReplace.Add("httpapplicationroutingzonename", "_httpapplicationroutingzonename")
                    $result = [WebRequestHelper]::InvokeWebRequest([Microsoft.PowerShell.Commands.WebRequestMethod]::Get, $uri, $headers, $null, $null, $propertiesToReplace); 
                    if(($null -ne $result) -and (($result | Measure-Object).Count -gt 0))
                    {
                        $this.ResourceObject = $result[0]
                    }
                }
                catch{
                    $err = $_
                    if($null -ne $err)
                    {
                        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[]] CheckClusterRBAC([controlresult] $controlresult)
    {
        if([Helpers]::CheckMember($this.ResourceObject,"Properties"))
        {
            if([Helpers]::CheckMember($this.ResourceObject.Properties,"enableRBAC") -and $this.ResourceObject.Properties.enableRBAC)
            {
                $controlResult.VerificationResult = [VerificationResult]::Passed
            }
            else
            {
                $controlResult.VerificationResult = [VerificationResult]::Failed
            }
        }

        return $controlResult;
    }

    hidden [controlresult[]] CheckAADEnabled([controlresult] $controlresult)
    {
        if([Helpers]::CheckMember($this.ResourceObject,"Properties"))
        {
            if([Helpers]::CheckMember($this.ResourceObject.Properties,"aadProfile") -and [Helpers]::CheckMember($this.ResourceObject.Properties.aadProfile,"clientAppID") -and [Helpers]::CheckMember($this.ResourceObject.Properties.aadProfile,"serverAppID") -and [Helpers]::CheckMember($this.ResourceObject.Properties.aadProfile,"tenantID"))
            {
                $controlResult.AddMessage([VerificationResult]::Passed,
                                        [MessageData]::new("AAD profile configuration details", $this.ResourceObject.Properties.aadProfile));
            }
            else
            {
                $controlResult.VerificationResult = [VerificationResult]::Failed
            }
        }

        return $controlResult;
    }

    hidden [controlresult[]] CheckKubernetesVersion([controlresult] $controlresult)
    {
        if(([Helpers]::CheckMember($this.ResourceObject,"Properties")) -and [Helpers]::CheckMember($this.ResourceObject.Properties,"kubernetesVersion"))
        {
            $requiredKubernetesVersion = $null
            $requiredKubernetesVersionPresent = $false
            <#
            $ResourceAppIdURI = [WebRequestHelper]::GetResourceManagerUrl();
            $AccessToken = [ContextHelper]::GetAccessToken($ResourceAppIdURI)
            $header = "Bearer " + $AccessToken
            $headers = @{"Authorization"=$header;"Content-Type"="application/json";}
 
            $uri=[system.string]::Format("{0}subscriptions/{1}/resourceGroups/{2}/providers/Microsoft.ContainerService/managedClusters/{3}/upgradeProfiles/default?api-version=2018-03-31",$ResourceAppIdURI,$this.SubscriptionContext.SubscriptionId, $this.ResourceContext.ResourceGroupName, $this.ResourceContext.ResourceName)
            $result = ""
            $err = $null
            try {
                $propertiesToReplace = @{}
                $propertiesToReplace.Add("httpapplicationroutingzonename", "_httpapplicationroutingzonename")
                $result = [WebRequestHelper]::InvokeWebRequest([Microsoft.PowerShell.Commands.WebRequestMethod]::Get, $uri, $headers, $null, $null, $propertiesToReplace);
                if(($null -ne $result) -and (($result | Measure-Object).Count -gt 0))
                {
                    $upgradeProfile = $result.properties.controlPlaneProfile.upgrades
                    $requiredKubernetsVersion = "0.0.0"
                    $upgradeProfile | Foreach-Object {
                        if([System.Version] $requiredKubernetsVersion -le [System.Version] $_)
                        {
                            $requiredKubernetsVersion = $_
                        }
                    }
                    $requiredKubernetsVersion = [System.Version] $requiredKubernetsVersion
                }
            }
            catch{
                #If any exception occurs, get required kubernetes version from config
                $requiredKubernetsVersion = [System.Version] $this.ControlSettings.KubernetesService.kubernetesVersion
            }
            #>

            $supportedKubernetesVersion = $this.ControlSettings.KubernetesService.kubernetesVersion
            $resourceKubernetesVersion = [System.Version] $this.ResourceObject.Properties.kubernetesVersion
            $supportedKubernetesVersion | ForEach-Object {
                if($resourceKubernetesVersion -eq [System.Version] $_){
                    $requiredKubernetesVersionPresent = $true
                }
            }

            if(-not $requiredKubernetesVersionPresent)
            {
                $controlResult.AddMessage([VerificationResult]::Failed,
                                        [MessageData]::new("AKS cluster is not running on required Kubernetes version."));
                $controlResult.AddMessage([MessageData]::new("Current Kubernetes version: ", $resourceKubernetesVersion.ToString()));
                $controlResult.AddMessage([MessageData]::new("Kubernetes cluster must be running on any one of the following versions: ", $supportedKubernetesVersion));

            }
            else
            {
                $controlResult.VerificationResult = [VerificationResult]::Passed
            }
        }

        return $controlResult;
    }

    hidden [controlresult[]] CheckMonitoringConfiguration([controlresult] $controlresult)
    {
        if([Helpers]::CheckMember($this.ResourceObject,"Properties"))
        {
            if([Helpers]::CheckMember($this.ResourceObject.Properties,"addonProfiles.omsagent") -and [Helpers]::CheckMember($this.ResourceObject.Properties.addonProfiles.omsagent,"config"))
            {
                if($this.ResourceObject.Properties.addonProfiles.omsagent.config -and $this.ResourceObject.Properties.addonProfiles.omsagent.enabled -eq $true)
                {
                    $controlResult.AddMessage([VerificationResult]::Passed,
                                        [MessageData]::new("Configuration of monitoring agent for resource " + $this.ResourceObject.name + " is ", $this.ResourceObject.Properties.addonProfiles.omsagent));
                }
                else
                {
                    $controlResult.AddMessage([VerificationResult]::Failed,
                                        [MessageData]::new("Monitoring agent is not enabled for resource " + $this.ResourceObject.name));
                }
            }
            else
            {
                $controlResult.AddMessage([VerificationResult]::Failed,
                                        [MessageData]::new("Monitoring agent is not configured for resource " + $this.ResourceObject.name));
            }
        }

        return $controlResult;
    }

    hidden [controlresult[]] CheckNodeOpenPorts([controlresult] $controlresult)
    {
        if([Helpers]::CheckMember($this.ResourceObject,"Properties") -and [Helpers]::CheckMember($this.ResourceObject.Properties,"nodeResourceGroup"))
        {
            $nodeRG = $this.ResourceObject.Properties.nodeResourceGroup
            $vms = Get-AzVM -ResourceGroupName $nodeRG -WarningAction SilentlyContinue 
            if(($vms | Measure-Object).Count -gt 0)
            {
                $isManual = $false
                $vulnerableNSGsWithRules = @();
                $effectiveNSG = $null;
                $openPortsList =@();
                $vmObject = $vms[0]
                $VMControlSettings = $this.ControlSettings.VirtualMachine.Linux
                $controlResult.AddMessage("Checking for Virtual Machine management ports",$VMControlSettings.ManagementPortList);
                $VMNICs = @();
                if($vmObject.NetworkProfile -and $vmObject.NetworkProfile.NetworkInterfaces)
                {
                    $vmObject.NetworkProfile.NetworkInterfaces | 
                    ForEach-Object {          
                        $currentNic = Get-AzResource -ResourceId $_.Id -ErrorAction SilentlyContinue
                        if($currentNic)
                        {
                            $nicResource = Get-AzNetworkInterface -Name $currentNic.Name `
                                                -ResourceGroupName $currentNic.ResourceGroupName `
                                                -ExpandResource NetworkSecurityGroup `
                                                -ErrorAction SilentlyContinue
                            if($nicResource)
                            {
                                $VMNICs += $nicResource;
                            }
                        }
                    }
                }

                $VMNICs | 
                    ForEach-Object {    
                    try
                    {
                        $effectiveNSG = Get-AzEffectiveNetworkSecurityGroup -NetworkInterfaceName $_.Name -ResourceGroupName $_.ResourceGroupName -WarningAction SilentlyContinue -ErrorAction Stop
                    }
                    catch
                    {
                        $isManual = $true
                        $statusCode = ($_.Exception).InnerException.Response.StatusCode;
                        if($statusCode -eq [System.Net.HttpStatusCode]::BadRequest -or $statusCode -eq [System.Net.HttpStatusCode]::Forbidden)
                        {                            
                            $controlResult.AddMessage(($_.Exception).InnerException.Message);    
                        }
                        else
                        {
                            throw $_
                        }
                    }
                    if($effectiveNSG)
                    {
                        $vulnerableRules = @()
                        
                        if($VMControlSettings -and $VMControlSettings.ManagementPortList)
                        {
                            Foreach($PortDetails in $VMControlSettings.ManagementPortList)
                            {
                                $portVulnerableRules = $this.CheckIfPortIsOpened($effectiveNSG,$PortDetails.Port)
                                if(($null -ne $portVulnerableRules) -and ($portVulnerableRules | Measure-Object).Count -gt 0)
                                {
                                    $openPortsList += $PortDetails
                                    $vulnerableRules += $openPortsList
                                }
                            }                            
                        }                
                        
                        if($vulnerableRules.Count -ne 0)
                        {
                            $vulnerableNSGsWithRules += @{
                                Association = $effectiveNSG.Association;
                                NetworkSecurityGroup = $effectiveNSG.NetworkSecurityGroup;
                                VulnerableRules = $vulnerableRules;
                                NicName = $_.Name
                            };
                        }                        
                    }                    
                }

                if($isManual)
                {
                    $controlResult.AddMessage([VerificationResult]::Manual, "Unable to check the NSG rules for some NICs. Please validate manually.");
                    #Setting this property ensures that this control result will not be considered for the central telemetry, as control does not have the required permissions
                    $controlResult.CurrentSessionContext.Permissions.HasRequiredAccess = $false;
                    if($vulnerableNSGsWithRules.Count -ne 0)
                    {
                        $controlResult.AddMessage([VerificationResult]::Manual, "Management ports are open on node VM. Please verify and remove the NSG rules in order to comply.", $vulnerableNSGsWithRules);
                    }
                }
                elseif($null -eq $effectiveNSG)
                {
                    #If the VM is connected to ERNetwork and there is no NSG, then we should not fail as this would directly conflict with the NSG control as well.
                    if($this.VMDetails.IsVMConnectedToERvNet)
                    {
                        $controlResult.AddMessage([VerificationResult]::Passed, "Node VM is connected ER Network. And no NSG found for Virtual Machine");  
                    }
                    else
                    {
                        $controlResult.AddMessage([VerificationResult]::Failed, "Verify if NSG is attached to node VM.");
                    }
                
                }
                else
                {
                    #If the VM is connected to ERNetwork or not and there is NSG, then teams should apply the recommendation and attest this control for now.
                    if($vulnerableNSGsWithRules.Count -eq 0)
                    {              
                        $controlResult.AddMessage([VerificationResult]::Passed, "No management ports are open on node VM");  
                    }
                    else
                    {
                        $controlResult.AddMessage("List of open ports: ",$openPortsList);
                        $controlResult.AddMessage([VerificationResult]::Verify, "Management ports are open on node VM. Please verify and remove the NSG rules in order to comply.", $vulnerableNSGsWithRules);

                        $controlResult.SetStateData("Management ports list on node VM", $vulnerableNSGsWithRules);
                    }
                }
            }
            else
            {
                $controlResult.AddMessage([VerificationResult]::Manual, "Unable to fetch node VM details. Please verify NSG rules manually on node VM.");
            }
        }
        
        return $controlResult;
    }

    hidden [PSObject] CheckIfPortIsOpened([PSObject] $effectiveNSG,[int] $port )
    {
        $vulnerableRules = @();
        $inbloundRules = $effectiveNSG.EffectiveSecurityRules | Where-Object { ($_.direction -eq "Inbound" -and $_.Name -notlike "defaultsecurityrules*") }
        foreach($securityRule in $inbloundRules){
            foreach($destPort in $securityRule.destinationPortRange) {
                $range =$destPort.Split("-")
                #For ex. if we provide the input 22 in the destination port range field, it will be interpreted as 22-22
                if($range.Count -eq 2) {
                    $startPort = $range[0]
                    $endPort = $range[1]
                    if(($port -ge $startPort -and $port -le $endPort) -and $securityRule.access.ToLower() -eq "deny")
                    {
                        break;
                    }
                    elseif(($port -ge $startPort -and $port -le $endPort) -and $securityRule.access.ToLower() -eq "allow")
                    {
                        $vulnerableRules += $securityRule
                    }
                    else
                    {
                        continue;
                    }
                }
                else 
                {
                    throw "Error while reading port range $($destPort)."
                }
    
            }
        }
        return $vulnerableRules;
    }

    hidden [controlresult[]] CheckHTTPAppRouting([controlresult] $controlresult)
    {
        if([Helpers]::CheckMember($this.ResourceObject,"Properties"))
        {
            if([Helpers]::CheckMember($this.ResourceObject.Properties,"Addonprofiles.httpApplicationRouting") -and $this.ResourceObject.Properties.Addonprofiles.httpApplicationRouting.enabled -eq $true)
            {
                
                $controlResult.AddMessage([VerificationResult]::Failed, "HTTP application routing is 'Enabled' for this cluster.");
                
            }
            else
            {
                $controlResult.AddMessage([VerificationResult]::Passed, "HTTP application routing is 'Disabled' for this cluster.");
            }
        }

        return $controlResult;
    }
}