Framework/Core/SVT/Services/ServiceFabric.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
Set-StrictMode -Version Latest 
class ServiceFabric : AzSVTBase
{       
    hidden [PSObject] $ResourceObject;
    hidden [string] $ClusterTagValue;
    hidden [PSObject] $ApplicationList;
    hidden [string] $DefaultTagName = "clusterName"
    hidden [string] $CertStoreLocation = "CurrentUser"
    hidden [string] $CertStoreName = "My"
    hidden [boolean] $IsSDKAvailable = $false

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

    hidden [PSObject] GetResourceObject()
    {
        if (-not $this.ResourceObject) 
        {
            $this.ResourceObject =  Get-AzResource -ResourceGroupName $this.ResourceContext.ResourceGroupName -ResourceType $this.ResourceContext.ResourceType -Name $this.ResourceContext.ResourceName    

            $this.ResourceObject.Tags.GetEnumerator() | Where-Object { $_.Key -eq $this.DefaultTagName } | ForEach-Object {$this.ClusterTagValue = $_.Value }
            
            # Check if Service Fabric SDK is installed
            try {

                $scanSource = [RemoteReportHelper]::GetScanSource();         
                if($scanSource -eq [ScanSource]::SpotCheck -and (Get-Command Connect-ServiceFabricCluster -ErrorAction SilentlyContinue)){    
                    $this.IsSDKAvailable = $true        
                }else
                {
                  $this.IsSDKAvailable = $false    
                }

            }catch {
                # No need to break execution
                # All controls which requires SDK to be present in user machine will be treated as manual controls
                $this.IsSDKAvailable = $false
            }
            
            
            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;
    }

    [ControlItem[]] ApplyServiceFilters([ControlItem[]] $controls)
    {
        $result = @();
        $VMType = "Windows"
        #Check VM type
        if([Helpers]::CheckMember($this.ResourceObject.Properties,"vmImage")){
            $VMType = $this.ResourceObject.Properties.vmImage
        }
        if($VMType -eq "Linux")
        {
            $result += $controls | Where-Object { $_.Tags -contains "Linux" };
        }
        else
        {
            $result += $controls | Where-Object { $_.Tags -contains "Windows" };;
        }
        return $result;
    }

    hidden [ControlResult] CheckSecurityMode([ControlResult] $controlResult)
    {
        $isCertificateEnabled = [Helpers]::CheckMember($this.ResourceObject.Properties,"certificate" ) 
        
        #Validate if primary certificate is enabled on cluster. Presence of certificate property value indicates, security mode is turned on.
        if($isCertificateEnabled)
        {            
            $controlResult.AddMessage([VerificationResult]::Passed,"Service Fabric cluster is secured with certificate", $this.ResourceObject.Properties.certificate);
        }
        else
        {            
            $controlResult.AddMessage([VerificationResult]::Failed,"Service Fabric cluster is not secured with certificate");
        }
        return $controlResult;    
    }

    hidden [ControlResult] CheckClusterCertificateSSL([ControlResult] $controlResult)
    {
        $managementEndpointUri = $this.ResourceObject.Properties.managementEndpoint
        $managementEndpointUriScheme = ([System.Uri]$managementEndpointUri).Scheme               

        #Validate if cluster management endpoint url is SSL enabled
        if($managementEndpointUriScheme -eq "https")
        {   
            #Hit web request to management endpoint uri and validate certificate trust level
            $request = [System.Net.HttpWebRequest]::Create($managementEndpointUri) 
            try
            {
                $request.GetResponse().Dispose()
                $controlResult.AddMessage([VerificationResult]::Passed,"Service Fabric cluster is protected with CA signed certificate");                    
            }
            catch [System.Net.WebException]
            {
                #Trust failure indicates self-signed certificate or domain mismatch certificate present on endpoint
                if ($_.Exception.Status -eq [System.Net.WebExceptionStatus]::TrustFailure)
                {                        
                    $controlResult.AddMessage([VerificationResult]::Verify,"Validate if self-signed certificate is not used for cluster management endpoint protection",$this.ResourceObject.Properties.managementEndpoint);
                    $controlResult.SetStateData("Management endpoint", $this.ResourceObject.Properties.managementEndpoint);
                }
                elseif($_.Exception.Message.Contains('403'))
                {
                    $controlResult.AddMessage([VerificationResult]::Passed,"Service Fabric cluster is protected with CA signed certificate");
                }
                else
                {                    
                    $controlResult.AddMessage([VerificationResult]::Manual,"Unable to Validate certificate details. Please verify manually that self-signed certificate is not used for cluster management endpoint protection",$this.ResourceObject.Properties.managementEndpoint);
                    $controlResult.AddMessage($_.Exception.Message);
                }
            }
        }
        else
        {
            $controlResult.AddMessage([VerificationResult]::Failed,"Service Fabric cluster is not protected by SSL")
        }
        return $controlResult;    
    }

    hidden [ControlResult] CheckAADClientAuthentication([ControlResult] $controlResult)
    {
        $isAADEnabled = [Helpers]::CheckMember($this.ResourceObject.Properties,"azureActiveDirectory")
        
        #Presence of 'AzureActiveDirectory' indicates, AAD authentication is enabled for client authentication
        if($isAADEnabled)
        {            
            $controlResult.AddMessage([VerificationResult]::Passed,"AAD is enabled for client authentication",$this.ResourceObject.Properties.azureActiveDirectory )
        }
        else
        {            
            $controlResult.AddMessage([VerificationResult]::Failed,"AAD is not enabled for client authentication")
        }

        return $controlResult
    }

    hidden [ControlResult] CheckClusterProtectionLevel([ControlResult] $controlResult)
    {
        $fabricSecuritySettings = $this.ResourceObject.Properties.fabricSettings | Where-Object {$_.Name -eq "Security"}

        #Absence of security settings indicates, secure mode is not enabled on cluster.
        if($null -ne $fabricSecuritySettings)
        {
            $clusterProtectionLevel = $fabricSecuritySettings.parameters | Where-Object { $_.name -eq "ClusterProtectionLevel"}
            if($null -ne $clusterProtectionLevel -and $clusterProtectionLevel.value -eq "EncryptAndSign")
            {
              $controlResult.AddMessage([VerificationResult]::Passed,"Cluster security is ON with 'EncryptAndSign' protection level",$clusterProtectionLevel);
            }
            else 
            {
              $controlResult.AddMessage([VerificationResult]::Failed,"Cluster security is not set with 'EncryptAndSign' protection level. Current protection level is :", $clusterProtectionLevel);
                $controlResult.SetStateData("Cluster protection level", $clusterProtectionLevel);
            }
        }
        else
        {
          $controlResult.AddMessage([VerificationResult]::Failed,"Cluster security is OFF");
        }

        return $controlResult
    }

    hidden [ControlResult[]] CheckNSGConfigurations([ControlResult] $controlResult)
    {
        $isVerify = $true;
        $nsgEnabledVNet = @{};
        $nsgDisabledVNet = @{};

        $virtualNetworkResources = $this.GetLinkedResources("Microsoft.Network/virtualNetworks") 
        if($virtualNetworkResources -ne $null)
        {
            #Iterate through all cluster linked VNet resources
            $virtualNetworkResources |ForEach-Object{            
                $virtualNetwork=Get-AzVirtualNetwork -ResourceGroupName $_.ResourceGroupName -Name $_.Name 
                $subnetConfig = Get-AzVirtualNetworkSubnetConfig -VirtualNetwork $virtualNetwork
                #Iterate through Subnet and validate if NSG is configured or not
                $subnetConfig | ForEach-Object{
                    $subnetName =$_.Name
                    $isCompliant =  ($null -ne $_.NetworkSecurityGroup)        
                    #If NSG is enabled on Subnet display all security rules applied
                    if($isCompliant)
                    {
                        $nsgResource = Get-AzResource -ResourceId $_.NetworkSecurityGroup.Id
                        $nsgResourceDetails = Get-AzNetworkSecurityGroup -ResourceGroupName $nsgResource.ResourceGroupName -Name $nsgResource.Name                
                        
                        $nsgEnabledVNet.Add($subnetName, $nsgResourceDetails)
                    }
                    #If NSG is not enabled on Subnet, fail the TCP with Subnet details
                    else
                    {
                        $nsgDisabledVNet.Add($subnetName, $_)
                        $isVerify = $false
                    } 
                }                
            }

            if($nsgEnabledVNet.Keys.Count -gt 0)
            {
                $nsgEnabledVNet.Keys  | Foreach-Object {
                    $controlResult.AddMessage("Validate NSG security rules applied on subnet '$_'",$nsgEnabledVNet[$_]);
                }
            }

            if($nsgDisabledVNet.Keys.Count -gt 0)
            {
                $nsgDisabledVNet.Keys  | Foreach-Object {
                    $controlResult.AddMessage("NSG is not configured on subnet '$_'",$nsgDisabledVNet[$_]);
                }
            }

            if($isVerify)
            {
                $controlResult.VerificationResult = [VerificationResult]::Verify;
            }
            else
            {
                $controlResult.VerificationResult = [VerificationResult]::Failed;
            }

            $NSGState = New-Object -TypeName PSObject 
            $NSGState | Add-Member -NotePropertyName NSGConfiguredSubnet -NotePropertyValue $nsgEnabledVNet
            $NSGState | Add-Member -NotePropertyName NSGNotConfiguredSubnet -NotePropertyValue $nsgDisabledVNet

            $controlResult.SetStateData("NSG security rules applied on subnet", $NSGState);
        }else{
            $controlResult.AddMessage("Not able to fetch details of VNet resources linked with cluster.");
            $controlResult.AddMessage("Manually verify that NSG is enabled on Subnet.");
            $controlResult.VerificationResult = [VerificationResult]::Manual;
        }
        

        return $controlResult        
    }

    hidden [ControlResult[]] CheckVmssDiagnostics([ControlResult] $controlResult)
    {
        $isPassed = $true;
        $diagnosticsEnabledScaleSet = @{};
        $diagnosticsDisabledScaleSet = @{};
        $vmssResources = $this.GetLinkedResources("Microsoft.Compute/virtualMachineScaleSets")
        #Iterate through cluster linked vmss resources
        $vmssResources | ForEach-Object{
            $VMScaleSetName = $_.Name    
            $nodeTypeResource = Get-AzVMss -ResourceGroupName  $_.ResourceGroupName -VMScaleSetName  $VMScaleSetName

            # Fetch diagnostics settings based on OS
            if($this.ResourceObject.Properties.vmImage -eq "Linux")
            {
                $diagnosticsSettings = $nodeTypeResource.VirtualMachineProfile.ExtensionProfile.Extensions  | ? { $_.Type -eq "LinuxDiagnostic" -and $_.Publisher -eq "Microsoft.OSTCExtensions" }                
            }
            else
            {
                   $diagnosticsSettings = $nodeTypeResource.VirtualMachineProfile.ExtensionProfile.Extensions  | ? { $_.Type -eq "IaaSDiagnostics" -and $_.Publisher -eq "Microsoft.Azure.Diagnostics" }
            }
            #Validate if diagnostics is enabled on vmss
            if($null -ne $diagnosticsSettings )
            {
                $diagnosticsEnabledScaleSet.Add($VMScaleSetName, $diagnosticsSettings)        
            }
            else
            {
                $isPassed = $false;
                $diagnosticsDisabledScaleSet.Add($VMScaleSetName, $diagnosticsSettings)        
            } 
        }

        if($diagnosticsEnabledScaleSet.Keys.Count -gt 0)
        {
            $diagnosticsEnabledScaleSet.Keys  | Foreach-Object {
                $controlResult.AddMessage("Diagnostics is enabled on Vmss '$_'",$diagnosticsEnabledScaleSet[$_]);
            }
        }

        if($diagnosticsDisabledScaleSet.Keys.Count -gt 0)
        {
            $diagnosticsDisabledScaleSet.Keys  | Foreach-Object {
                $controlResult.AddMessage("Diagnostics is disabled on Vmss '$_'",$diagnosticsDisabledScaleSet[$_]);
            }
        }

        if($isPassed)
        {
            $controlResult.VerificationResult = [VerificationResult]::Passed;
        }
        else
        {
            $controlResult.VerificationResult = [VerificationResult]::Failed;
            $controlResult.SetStateData("Diagnostics is disabled on Vmss", $diagnosticsDisabledScaleSet);
        }
        return $controlResult        
    }
    hidden [ControlResult[]] CheckReverseProxyPort([ControlResult] $controlResult)
    {
        # add attestation details
        $isPassed = $true;
        $reverseProxyEnabledNode = @{};
        $reverseProxyDisabledNode = @();
        $reverseProxyExposedNode = @{};
        $nodeTypes= $this.ResourceObject.Properties.nodeTypes
        #Iterate through each node
        $nodeTypes | ForEach-Object{

            if([Helpers]::CheckMember($_,"reverseProxyEndpointPort"))
            {
                $reverseProxyEnabledNode.Add($_.name, $_.reverseProxyEndpointPort)
            }else{
                $reverseProxyDisabledNode += $_.name
            }
        }
        # if reverse proxy is not enabled in any node, pass TCP
        if(($reverseProxyEnabledNode | Measure-Object).Count -gt 0)
        {
            $lbWithBackendPorts = @{}
            $loadBalancerResources = $this.GetLinkedResources("Microsoft.Network/loadBalancers")
            #Collect all open ports on load balancer
            $loadBalancerResources | ForEach-Object{
                $loadBalancerBackendPorts = @()
                $loadBalancerResource = Get-AzLoadBalancer -Name $_.Name -ResourceGroupName $_.ResourceGroupName
                $loadBalancingRules = @($loadBalancerResource.FrontendIpConfigurations | ? { $null -ne $_.PublicIpAddress } | ForEach-Object { $_.LoadBalancingRules })
            
                $loadBalancingRules | ForEach-Object {
                    $loadBalancingRuleId = $_.Id;
                    $loadBalancingRule = $loadBalancerResource.LoadBalancingRules | ? { $_.Id -eq  $loadBalancingRuleId } | Select-Object -First 1
                    $loadBalancerBackendPorts += $loadBalancingRule.BackendPort;
                };  
                if($loadBalancerBackendPorts.Count -gt 0)
                {   
                
                  if([Helpers]::CheckMember($loadBalancerResource.BackendAddressPools,"BackendIpConfigurations") -and  ($loadBalancerResource.BackendAddressPools.BackendIpConfigurations | Measure-Object).Count -gt 0){
                    $backEndIpConfiguration = $loadBalancerResource.BackendAddressPools.BackendIpConfigurations | Select -First 1
                    $pattern = "providers/Microsoft.Compute/virtualMachineScaleSets/(.*?)/"
                    $result = [regex]::match($backEndIpConfiguration.Id, $pattern)
                    if($result.Success){
                        $nodeName = $result.Groups[1].Value
                        $lbWithBackendPorts.Add($nodeName, $loadBalancerBackendPorts)
                    }

                  }
                  
                } 
            }
            #If no ports open, Pass the TCP
            if($lbWithBackendPorts.Count -eq 0)
            {
                $controlResult.AddMessage("No ports enabled in load balancer.")  
                $controlResultList += $controlResult      
            }
            #If Ports are open for public in load balancer, check if any reverse proxy port is exposed
            else
            {
                $reverseProxyEnabledNode.Keys  | Foreach-Object {
                    $loadBalancerBackendPorts = @()
                    $nodeName = $_
                    $lbWithBackendPorts.Keys | ForEach-Object{
                        if($_ -eq $nodeName){
                            $loadBalancerBackendPorts = $lbWithBackendPorts[$_]
                        }
                    }
                    if($loadBalancerBackendPorts.Count -gt 0 -and  $loadBalancerBackendPorts.Contains( [Int32] $reverseProxyEnabledNode[$_]))
                    {
                        $isPassed = $false;
                        $controlResult.AddMessage("Reverse proxy port is publicly exposed for node '$_'");
                        $reverseProxyExposedNode.Add($_, $reverseProxyEnabledNode[$_])
                    }else{
                        $controlResult.AddMessage("Reverse proxy port is not publicly exposed for node '$_'.") 
                    }
                    
                }
            }
        }else{
            $controlResult.AddMessage("Reverse proxy service is not enabled in cluster.") 
        }
        if($isPassed)
        {
            
            $controlResult.VerificationResult = [VerificationResult]::Passed;
        }
        else
        {
            $controlResult.VerificationResult = [VerificationResult]::Failed;
            $controlResult.SetStateData("Reverse proxy port is publicly exposed", $reverseProxyExposedNode);
        }
        return $controlResult
    }

    hidden [ControlResult] CheckClusterUpgradeMode([ControlResult] $controlResult)
    {
        if([Helpers]::CheckMember($this.ResourceObject.Properties,"upgradeMode") -and $this.ResourceObject.Properties.upgradeMode -eq "Automatic")
        {            
            $controlResult.AddMessage([VerificationResult]::Passed,"Upgrade mode for cluster is set to automatic." )
        }
        else
        {            
            $controlResult.AddMessage([VerificationResult]::Failed,"Upgrade mode for cluster is set to manual.")
        }

        return $controlResult
    }

    hidden [ControlResult[]] CheckStatefulServiceReplicaSetSize([ControlResult] $controlResult)
    {   
        $isConnectionSuccessful = $false
        if($this.IsSDKAvailable -eq $true)
        {
            #Function to validate authentication and connect with Service Fabric cluster
            $sfCluster = $null       
            $uri = ([System.Uri]$this.ResourceObject.Properties.managementEndpoint).Host                
            $primaryNodeType = $this.ResourceObject.Properties.nodeTypes | Where-Object { $_.isPrimary -eq $true }
                    
            $ClusterConnectionUri = $uri +":"+ $primaryNodeType.clientConnectionEndpointPort
            $isClusterSecure =  [Helpers]::CheckMember($this.ResourceObject.Properties,"certificate" )               
                    
            if($isClusterSecure)
            {
                    $serviceFabricCertificate = $this.ResourceObject.Properties.certificate              
                    $CertThumbprint= $this.ResourceObject.Properties.certificate.thumbprint
                    $serviceFabricAAD = $null
                    if([Helpers]::CheckMember($this.ResourceObject.Properties,"azureActiveDirectory" ))
                    {
                        $serviceFabricAAD =$this.ResourceObject.Properties.azureActiveDirectory
                    }  
                    if($null -ne $serviceFabricAAD)
                    {
                        try
                        {
                            $this.PublishCustomMessage("Connecting Service Fabric using AAD...")
                            $sfCluster = Connect-ServiceFabricCluster -ConnectionEndpoint $ClusterConnectionUri -AzureActiveDirectory -ServerCertThumbprint $CertThumbprint #-SecurityToken "
                            $isConnectionSuccessful = $true
                            $this.PublishCustomMessage("Connection using AAD is successful.")
                        }
                        catch
                        {
                            $this.PublishCustomMessage("You may not have permission to connect with cluster", [MessageType]::Warning);
                        }
                    }              
                    else
                    {
                        $this.PublishCustomMessage("Validating if cluster certificate present on machine...")
                        $IsCertPresent = (Get-ChildItem -Path "Cert:\$($this.CertStoreLocation)\$($this.CertStoreName)" | Where-Object {$_.Thumbprint -eq $CertThumbprint }| Measure-Object).Count                   
                        if($IsCertPresent)
                        {
                           try
                           {
                              $this.PublishCustomMessage("Connecting Service Fabric using certificate")
                              $sfCluster = Connect-serviceFabricCluster -ConnectionEndpoint $ClusterConnectionUri -KeepAliveIntervalInSec 10 -X509Credential -ServerCertThumbprint $CertThumbprint -FindType FindByThumbprint -FindValue $CertThumbprint -StoreLocation $this.CertStoreLocation -StoreName $this.CertStoreName 
                              $isConnectionSuccessful = $true
                           }catch
                           {
                               $this.PublishCustomMessage("Cannot connect with Service Fabric cluster using cluster certificate. Verify that valid cluster certificate is present in 'CurrentUser' location.", [MessageType]::Warning);    
                           }
                                                
                        }
                        else
                        {
                            $this.PublishCustomMessage("Cannot connect with Service Fabric cluster due to unavailability of cluster certificate in local machine. Validate cluster certificate is present in 'CurrentUser' location.", [MessageType]::Warning);                    
                        }
                    }                    
            }
            else
            {
                $sfCluster = Connect-serviceFabricCluster -ConnectionEndpoint $ClusterConnectionUri
                $isConnectionSuccessful = $true
                $this.PublishCustomMessage("Service Fabric connection is successful");
            }
            
            try
            {
              $this.ApplicationList = Get-ServiceFabricApplication -ErrorAction SilentlyContinue
            }catch
            {
               # No need to break execution, handled in next condition
            }

            $isPassed = $true;
            $complianteServices = @{};
            $nonComplianteServices = @{};
            #Iterate through the applications present in cluster
            if($isConnectionSuccessful -eq $false)
            {
              $controlResult.AddMessage([VerificationResult]::Manual,"Cannot connect with Service Fabric cluster.")
              $controlResult.CurrentSessionContext.Permissions.HasRequiredAccess = $false;

            }elseif($this.ApplicationList)
            {
                $this.ApplicationList | ForEach-Object{
                    $serviceFabricApplication = $_

                    Get-ServiceFabricService -ApplicationName $serviceFabricApplication.ApplicationName | ForEach-Object{                
                        $serviceName = $_.ServiceName 
                        $serviceDescription = Get-ServiceFabricServiceDescription -ServiceName $_.ServiceName 
                        #Filter application with Stateful service type
                        if($serviceDescription.ServiceKind -eq "Stateful")
                        {
                            #Validate minimum replica and target replica size for each service
                            $isCompliant = !($serviceDescription.MinReplicaSetSize -lt 3 -or $serviceDescription.TargetReplicaSetSize -lt 3)
                            
                            $stateObject = "" | Select-Object "MinReplicaSetSize" ,"TargetReplicaSetSize"
                            $stateObject.MinReplicaSetSize = $serviceDescription.MinReplicaSetSize
                            $stateObject.TargetReplicaSetSize = $serviceDescription.TargetReplicaSetSize
                            if($isCompliant)
                            {
                                $complianteServices.Add($serviceName, $stateObject)
                            } 
                            else
                            { 
                                $isPassed = $False
                                $nonComplianteServices.Add($serviceName, $stateObject)
                            }
                        }                
                    }
                }

                if($complianteServices.Keys.Count -gt 0)
                {
                    $controlResult.AddMessage("Replica set size for below services are complaint");
                    $complianteServices.Keys  | Foreach-Object {
                        $controlResult.AddMessage("Replica set size details for service '$_'",$complianteServices[$_]);
                    }
                }

                if($nonComplianteServices.Keys.Count -gt 0)
                {
                    $controlResult.AddMessage("Replica set size for below services are non-complaint");
                    $nonComplianteServices.Keys  | Foreach-Object {
                        $controlResult.AddMessage("Replica set size details for service '$_'",$nonComplianteServices[$_]);
                    }
                }

                if($isPassed)
                {
                    $controlResult.VerificationResult = [VerificationResult]::Passed;
                }
                else
                {
                    $controlResult.VerificationResult = [VerificationResult]::Failed;
                    $controlResult.SetStateData("Replica set size are non-complaint for", $nonComplianteServices);
                }
            }
            else
            {
                $controlResult.AddMessage([VerificationResult]::Passed,"No stateful service found.")
            }
        }else{
            
            $scanSource = [RemoteReportHelper]::GetScanSource();
            if($scanSource -eq [ScanSource]::SpotCheck)
            { 
               $controlResult.AddMessage("Service Fabric SDK is not present in user machine. To evaluate this control SDK should be available on user machine.")
            }
            $controlResult.CurrentSessionContext.Permissions.HasRequiredAccess = $false;
            $controlResult.VerificationResult = [VerificationResult]::Manual;
        }
        
        return $controlResult;
    }

    hidden [ControlResult[]] CheckStatelessServiceInstanceCount([ControlResult] $controlResult)
    {
        $isConnectionSuccessful = $false
        if($this.IsSDKAvailable -eq $true)
        {
           
            #Function to validate authentication and connect with Service Fabric cluster
            $sfCluster = $null       
            $uri = ([System.Uri]$this.ResourceObject.Properties.managementEndpoint).Host                
            $primaryNodeType = $this.ResourceObject.Properties.nodeTypes | Where-Object { $_.isPrimary -eq $true }
                    
            $ClusterConnectionUri = $uri +":"+ $primaryNodeType.clientConnectionEndpointPort
            $isClusterSecure =  [Helpers]::CheckMember($this.ResourceObject.Properties,"certificate" )               
                    
            if($isClusterSecure)
            {
                    $serviceFabricCertificate = $this.ResourceObject.Properties.certificate              
                    $CertThumbprint= $this.ResourceObject.Properties.certificate.thumbprint
                    $serviceFabricAAD = $null
                    if([Helpers]::CheckMember($this.ResourceObject.Properties,"azureActiveDirectory" ))
                    {
                        $serviceFabricAAD =$this.ResourceObject.Properties.azureActiveDirectory
                    }  
                    if($null -ne $serviceFabricAAD)
                    {
                        try
                        {
                            $this.PublishCustomMessage("Connecting Service Fabric using AAD...")
                            $sfCluster = Connect-ServiceFabricCluster -ConnectionEndpoint $ClusterConnectionUri -AzureActiveDirectory -ServerCertThumbprint $CertThumbprint #-SecurityToken "
                            $isConnectionSuccessful = $true
                            $this.PublishCustomMessage("Connection using AAD is successful.")
                        }
                        catch
                        {
                            $this.PublishCustomMessage("You may not have permission to connect with cluster", [MessageType]::Warning);
                        }
                    }              
                    else
                    {
                        $this.PublishCustomMessage("Validating if cluster certificate present on machine...")
                        $IsCertPresent = (Get-ChildItem -Path "Cert:\$($this.CertStoreLocation)\$($this.CertStoreName)" | Where-Object {$_.Thumbprint -eq $CertThumbprint }| Measure-Object).Count                   
                        if($IsCertPresent)
                        {
                           try
                           {
                              $this.PublishCustomMessage("Connecting Service Fabric using certificate")
                              $sfCluster = Connect-serviceFabricCluster -ConnectionEndpoint $ClusterConnectionUri -KeepAliveIntervalInSec 10 -X509Credential -ServerCertThumbprint $CertThumbprint -FindType FindByThumbprint -FindValue $CertThumbprint -StoreLocation $this.CertStoreLocation -StoreName $this.CertStoreName 
                              $isConnectionSuccessful = $true
                           }catch
                           {
                               $this.PublishCustomMessage("Cannot connect with Service Fabric cluster using cluster certificate. Verify that valid cluster certificate is present in 'CurrentUser' location.", [MessageType]::Warning);    
                           }
                                                
                        }
                        else
                        {
                            $this.PublishCustomMessage("Cannot connect with Service Fabric cluster due to unavailability of cluster certificate in local machine. Validate cluster certificate is present in 'CurrentUser' location.", [MessageType]::Warning);                    
                        }
                    }                    
            }
            else
            {
                $sfCluster = Connect-serviceFabricCluster -ConnectionEndpoint $ClusterConnectionUri
                $isConnectionSuccessful = $true
                $this.PublishCustomMessage("Service Fabric connection is successful");
            }

            try
            {
                $this.ApplicationList = Get-ServiceFabricApplication -ErrorAction SilentlyContinue
            }catch
            {
               # No need to break execution, handled in next condition
            }
            
            $isPassed = $true;
            $complianteServices = @{};
            $nonComplianteServices = @{};
               
            if($isConnectionSuccessful -eq $false)
            {
              $controlResult.AddMessage([VerificationResult]::Manual,"Cannot connect with Service Fabric cluster.")
              $controlResult.CurrentSessionContext.Permissions.HasRequiredAccess = $false;
            }elseif($this.ApplicationList)
            {
                #Iterate through the applications present in cluster
                $this.ApplicationList | ForEach-Object{
                    $serviceFabricApplication = $_
                    Get-ServiceFabricService -ApplicationName $serviceFabricApplication.ApplicationName | 
                    ForEach-Object{
                        $serviceName = $_.ServiceName                 
                        $serviceDescription = Get-ServiceFabricServiceDescription -ServiceName $serviceName 
                        #Filter application with Stateless service type
                        if($serviceDescription.ServiceKind -eq "Stateless")
                        {     
                            #Validate instancecount it -1 (auto) or greater than equal to 3
                            $isCompliant = ($serviceDescription.InstanceCount -eq -1 -or $serviceDescription.InstanceCount -ge 3)
                            if($isCompliant)
                            {
                                $complianteServices.Add($serviceName, $serviceDescription.InstanceCount)
                            } 
                            else
                            { 
                                $isPassed = $False
                                $nonComplianteServices.Add($serviceName, $serviceDescription.InstanceCount)
                            }
                            
                        } 
                    } 
                }
                if($complianteServices.Keys.Count -gt 0)
                {
                    $controlResult.AddMessage("Instance count for below services are complaint");
                    $complianteServices.Keys  | Foreach-Object {
                        $controlResult.AddMessage("Instance count details for service '$_'",$complianteServices[$_]);
                    }
                }
    
                if($nonComplianteServices.Keys.Count -gt 0)
                {
                    $controlResult.AddMessage("Instance count for below services are non-complaint");
                    $nonComplianteServices.Keys  | Foreach-Object {
                        $controlResult.AddMessage("Instance count details for service '$_'",$nonComplianteServices[$_]);
                    }
                }
    
                if($isPassed)
                {
                    $controlResult.VerificationResult = [VerificationResult]::Passed;
                }
                else
                {
                    $controlResult.VerificationResult = [VerificationResult]::Failed;
                    $controlResult.SetStateData("Instance count are non-complaint for", $nonComplianteServices);
                }
            }
            else
            {
                $controlResult.AddMessage([VerificationResult]::Passed,"No stateless service found.")
            } 
        }else{

             $scanSource = [RemoteReportHelper]::GetScanSource();
             if($scanSource -eq [ScanSource]::SpotCheck)
             { 
                $controlResult.AddMessage("Service Fabric SDK is not present in user machine. To evaluate this control SDK should be available on user machine.")
             }
             $controlResult.CurrentSessionContext.Permissions.HasRequiredAccess = $false;
             $controlResult.VerificationResult = [VerificationResult]::Manual;
        }
        
        
        return $controlResult;        
    }

    hidden [ControlResult[]] CheckPublicEndpointSSL([ControlResult] $controlResult)
    {    
        $isConnectionSuccessful = $false
        if($this.IsSDKAvailable -eq $true)
        {          
            #Function to validate authentication and connect with Service Fabric cluster
            $sfCluster = $null       
            $uri = ([System.Uri]$this.ResourceObject.Properties.managementEndpoint).Host                
            $primaryNodeType = $this.ResourceObject.Properties.nodeTypes | Where-Object { $_.isPrimary -eq $true }
                    
            $ClusterConnectionUri = $uri +":"+ $primaryNodeType.clientConnectionEndpointPort
            $isClusterSecure =  [Helpers]::CheckMember($this.ResourceObject.Properties,"certificate" )               
                    
            if($isClusterSecure)
            {
                    $serviceFabricCertificate = $this.ResourceObject.Properties.certificate              
                    $CertThumbprint= $this.ResourceObject.Properties.certificate.thumbprint
                    $serviceFabricAAD = $null
                    if([Helpers]::CheckMember($this.ResourceObject.Properties,"azureActiveDirectory" ))
                    {
                        $serviceFabricAAD =$this.ResourceObject.Properties.azureActiveDirectory
                    }  
                    if($null -ne $serviceFabricAAD)
                    {
                        try
                        {
                            $this.PublishCustomMessage("Connecting Service Fabric using AAD...")
                            $sfCluster = Connect-ServiceFabricCluster -ConnectionEndpoint $ClusterConnectionUri -AzureActiveDirectory -ServerCertThumbprint $CertThumbprint #-SecurityToken "
                            $isConnectionSuccessful = $true
                            $this.PublishCustomMessage("Connection using AAD is successful.")
                        }
                        catch
                        {
                            $this.PublishCustomMessage("You may not have permission to connect with cluster", [MessageType]::Warning);
                        }
                    }              
                    else
                    {
                        $this.PublishCustomMessage("Validating if cluster certificate present on machine...")
                        $IsCertPresent = (Get-ChildItem -Path "Cert:\$($this.CertStoreLocation)\$($this.CertStoreName)" | Where-Object {$_.Thumbprint -eq $CertThumbprint }| Measure-Object).Count                   
                        if($IsCertPresent)
                        {
                           try
                           {
                              $this.PublishCustomMessage("Connecting Service Fabric using certificate")
                              $sfCluster = Connect-serviceFabricCluster -ConnectionEndpoint $ClusterConnectionUri -KeepAliveIntervalInSec 10 -X509Credential -ServerCertThumbprint $CertThumbprint -FindType FindByThumbprint -FindValue $CertThumbprint -StoreLocation $this.CertStoreLocation -StoreName $this.CertStoreName 
                              $isConnectionSuccessful = $true
                           }catch
                           {
                               $this.PublishCustomMessage("Cannot connect with Service Fabric cluster using cluster certificate. Verify that valid cluster certificate is present in 'CurrentUser' location.", [MessageType]::Warning);    
                           }
                                                
                        }
                        else
                        {
                            $this.PublishCustomMessage("Cannot connect with Service Fabric cluster due to unavailability of cluster certificate in local machine. Validate cluster certificate is present in 'CurrentUser' location.", [MessageType]::Warning);                    
                        }
                    }                    
            }
            else
            {
                $sfCluster = Connect-serviceFabricCluster -ConnectionEndpoint $ClusterConnectionUri
                $isConnectionSuccessful = $true
                $this.PublishCustomMessage("Service Fabric connection is successful");
            }

            try
            {
                $this.ApplicationList = Get-ServiceFabricApplication -ErrorAction SilentlyContinue
            }catch
            {
               #No need to break execution, handled in next condition
            }
            
            $isManual = $false;
            $isPassed = $true;
            $compliantPort = @{};
            $nonCompliantPort = @{};

            $loadBalancerBackendPorts = @()
            $loadBalancerResources = $this.GetLinkedResources("Microsoft.Network/loadBalancers")
            #Collect all open ports on load balancer
            $loadBalancerResources | ForEach-Object{
                $loadBalancerResource = Get-AzLoadBalancer -Name $_.Name -ResourceGroupName $_.ResourceGroupName
                $loadBalancingRules = @($loadBalancerResource.FrontendIpConfigurations | ? { $null -ne $_.PublicIpAddress } | ForEach-Object { $_.LoadBalancingRules })
            
                $loadBalancingRules | ForEach-Object {
                    $loadBalancingRuleId = $_.Id;
                    $loadBalancingRule = $loadBalancerResource.LoadBalancingRules | ? { $_.Id -eq  $loadBalancingRuleId } | Select-Object -First 1
                    $loadBalancerBackendPorts += $loadBalancingRule.BackendPort;
                };   
            }
            
            #If no ports open, Pass the TCP
            if($loadBalancerBackendPorts.Count -eq 0)
            {
                $controlResult.AddMessage("No ports enabled.")       
            }
            #If Ports are open for public in load balancer, map load balancer ports with application endpoint ports and validate if SSL is enabled.
            else
            {
        
               if($isConnectionSuccessful -eq $false)
               {
                    $isManual = $true;
                    $controlResult.AddMessage("Cannot connect with Service Fabric cluster.")
                    $controlResult.CurrentSessionContext.Permissions.HasRequiredAccess = $false;
               }
               elseif($this.ApplicationList)
                {
                    $controlResult.AddMessage("List of publicly exposed port",$loadBalancerBackendPorts) 

                    $this.ApplicationList | 
                    ForEach-Object{
                        $serviceFabricApplication = $_
                        Get-ServiceFabricServiceType -ApplicationTypeName $serviceFabricApplication.ApplicationTypeName -ApplicationTypeVersion $serviceFabricApplication.ApplicationTypeVersion | 
                        ForEach-Object{
                            $currentService = $_
                            $serviceManifest = [xml](Get-ServiceFabricServiceManifest -ApplicationTypeName $serviceFabricApplication.ApplicationTypeName -ApplicationTypeVersion $serviceFabricApplication.ApplicationTypeVersion -ServiceManifestName $_.ServiceManifestName)
                            if([Helpers]::CheckMember($serviceManifest.ServiceManifest,"Resources.Endpoints"))
                            {
                                $serviceManifest.ServiceManifest.Resources.Endpoints.ChildNodes | 
                                ForEach-Object{
                                    $endpoint = $_
                                    $serviceTypeName = $currentService.ServiceTypeName
                            
                                    if(-not [Helpers]::CheckMember($endpoint,"Port"))
                                    {
                                        #Add message
                                        #$childControlResult.AddMessage([VerificationResult]::Passed)
                                    }
                                    else
                                    {
                                        if($loadBalancerBackendPorts.Contains([Int32] $endpoint.Port) )
                                        {                      
                                            if([Helpers]::CheckMember($endpoint,"Protocol") -and $endpoint.Protocol -eq "https"){  
                                                $compliantPort.Add($serviceFabricApplication.ApplicationName.OriginalString + "/" + $serviceTypeName + "/"+$endpoint.Name,  $endpoint.Port) 
                                                
                                             }
                                            elseif([Helpers]::CheckMember($endpoint,"Protocol") -and $endpoint.Protocol -eq "http"){  
                                                $isPassed = $false;
                                        
                                                $nonCompliantPort.Add($serviceFabricApplication.ApplicationName.OriginalString + "/" + $serviceTypeName + "/"+$endpoint.Name,  $endpoint.Port) 
                                            }
                                            else {  
                                                $isPassed = $false;
                                                $nonCompliantPort.Add($serviceFabricApplication.ApplicationName.OriginalString + "/" + $serviceTypeName + "/"+$endpoint.Name,  $endpoint.Port) 
                                            
                                             }                            
                                        }
                                        else
                                        {   
                                            $compliantPort.Add($serviceFabricApplication.ApplicationName.OriginalString + "/" + $serviceTypeName + "/"+$endpoint.Name,  $endpoint.Port)                     
                                            
                                        }
                                    }                             
                                } 
                            }
                                          
                        }
                    }             
                }
                else
                {
                    $controlResult.AddMessage("No service found.")
                }    
            }     

            if($compliantPort.Keys.Count -gt 0)
            {
                $controlResult.AddMessage("Following endpoint(s) are compliant");
                $compliantPort.Keys  | Foreach-Object {
                    $controlResult.AddMessage("Endpoint: '$_' Port: $($compliantPort[$_])");
                }
            }

            if($nonCompliantPort.Keys.Count -gt 0)
            {
                $controlResult.AddMessage("Following publicly exposed endpoint(s) are not secured using SSL");
                $nonCompliantPort.Keys  | Foreach-Object {
                    $controlResult.AddMessage("EndPoint: '$_' Port: $($nonCompliantPort[$_])");
                }
            }

            if($isManual)
            {
                $controlResult.VerificationResult = [VerificationResult]::Manual;
            }
            elseif($isPassed)
            {
                $controlResult.VerificationResult = [VerificationResult]::Passed;
            }
            else
            {
                $controlResult.VerificationResult = [VerificationResult]::Failed;
                $controlResult.SetStateData("Following ports are non-complaint", $nonCompliantPort);
            }
        }else{
            
            $scanSource = [RemoteReportHelper]::GetScanSource();
            if($scanSource -eq [ScanSource]::SpotCheck)
            { 
               $controlResult.AddMessage("Service Fabric SDK is not present in user machine. To evaluate this control SDK should be available on user machine.")
            }
            $controlResult.CurrentSessionContext.Permissions.HasRequiredAccess = $false;
            $controlResult.VerificationResult = [VerificationResult]::Manual;
        }
    
            
        return $controlResult       
    }
    [void] CheckClusterAccess()
    {    
        #Function to validate authentication and connect with Service Fabric cluster
        $sfCluster = $null       
        $uri = ([System.Uri]$this.ResourceObject.Properties.managementEndpoint).Host                
        $primaryNodeType = $this.ResourceObject.Properties.nodeTypes | Where-Object { $_.isPrimary -eq $true }
                
        $ClusterConnectionUri = $uri +":"+ $primaryNodeType.clientConnectionEndpointPort
        $this.PublishCustomMessage("Connecting with Service Fabric cluster...")
        $this.PublishCustomMessage("Validating if Service Fabric is secure...")
        
        $isClusterSecure =  [Helpers]::CheckMember($this.ResourceObject.Properties,"certificate" )               
                
        if($isClusterSecure)
        {
            $serviceFabricCertificate = $this.ResourceObject.Properties.certificate              
            $this.PublishCustomMessage("Service Fabric is secure")
            $CertThumbprint= $this.ResourceObject.Properties.certificate.thumbprint
            $serviceFabricAAD = $null
            if([Helpers]::CheckMember($this.ResourceObject.Properties,"azureActiveDirectory" ))
            {
             $serviceFabricAAD =$this.ResourceObject.Properties.azureActiveDirectory
            }  
            if($null -ne $serviceFabricAAD)
            {
                try
                {
                    $this.PublishCustomMessage("Connecting Service Fabric using AAD...")
                    $sfCluster = Connect-ServiceFabricCluster -ConnectionEndpoint $ClusterConnectionUri -AzureActiveDirectory -ServerCertThumbprint $CertThumbprint #-SecurityToken "
                     $this.PublishCustomMessage("Connection using AAD is successful.")
                }
                catch
                {
                    throw ([SuppressedException]::new(("You may not have permission to connect with cluster"), [SuppressedExceptionType]::InvalidOperation))
                }
            }              
            else
            {
                $this.PublishCustomMessage("Validating if cluster certificate present on machine...")
                $IsCertPresent = (Get-ChildItem -Path "Cert:\$($this.CertStoreLocation)\$($this.CertStoreName)" | Where-Object {$_.Thumbprint -eq $CertThumbprint }| Measure-Object).Count                   
                if($IsCertPresent)
                {
                    $this.PublishCustomMessage("Connecting Service Fabric using certificate")
                    $sfCluster = Connect-serviceFabricCluster -ConnectionEndpoint $ClusterConnectionUri -KeepAliveIntervalInSec 300 -X509Credential -ServerCertThumbprint $CertThumbprint -FindType FindByThumbprint -FindValue $CertThumbprint -StoreLocation $this.CertStoreLocation -StoreName $this.CertStoreName 
                }
                else
                {
                    throw ([SuppressedException]::new(("Cannot connect with Service Fabric due to unavailability of cluster certificate in local machine. Validate cluster certificate is present in 'CurrentUser' location."), [SuppressedExceptionType]::InvalidOperation))
                }
            }                    
        }
        else
        {
            $this.PublishCustomMessage("Service Fabric is unsecure");
            $sfCluster = Connect-serviceFabricCluster -ConnectionEndpoint $ClusterConnectionUri
            $this.PublishCustomMessage("Service Fabric connection is successful");
        }
    }

    [PSObject] GetLinkedResources([string] $resourceType)
    {
        return  Get-AzResource -TagName $this.DefaultTagName -TagValue $this.ClusterTagValue | Where-Object { ($_.ResourceType -EQ $resourceType) -and ($_.ResourceGroupName -eq $this.ResourceContext.ResourceGroupName) }
    }    

}