Framework/Core/SVT/Services/VirtualMachine.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
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
using namespace Microsoft.Azure.Commands.Network.Models
using namespace Microsoft.Azure.Commands.Compute.Models
using namespace Microsoft.Azure.Management.Compute.Models
Set-StrictMode -Version Latest 

class VirtualMachine: SVTBase
{       
    hidden [PSVirtualMachine] $ResourceObject;
    hidden [PSNetworkInterface[]] $VMNICs = $null;
    hidden [PSObject] $ASCSettings = $null;
    hidden [bool] $IsVMDeallocated = $false
    hidden [VMDetails] $VMDetails = [VMDetails]::new()
    hidden [PSObject] $VMControlSettings = $null;
    hidden [string] $Workspace = "";

    VirtualMachine([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): 
        Base($subscriptionId, $resourceGroupName, $resourceName) 
    { 
        $this.GetResourceObject();    
        $this.GetVMDetails();
        $metadata= [PSObject]::new();
        $metadata| Add-Member -Name VMDetails -Value $this.VMDetails -MemberType NoteProperty;
        $metadata| Add-Member -Name VMASCDetails -Value $this.ASCSettings -MemberType NoteProperty;                
        $this.AddResourceMetadata($metadata);    
    }
    
    VirtualMachine([string] $subscriptionId, [SVTResource] $svtResource): 
        Base($subscriptionId, $svtResource) 
    { 
        $this.GetResourceObject();
        $this.GetVMDetails();
        $metadata= [PSObject]::new();
        $metadata| Add-Member -Name VMDetails -Value $this.VMDetails -MemberType NoteProperty;
        $metadata| Add-Member -Name VMASCDetails -Value $this.ASCSettings -MemberType NoteProperty;                
        $this.AddResourceMetadata($metadata);        
        
        #OS type must always be present in configuration setting file
        if([Helpers]::CheckMember($this.ControlSettings.VirtualMachine, $this.VMDetails.OSType)){
            $this.VMControlSettings = $this.ControlSettings.VirtualMachine.$($this.VMDetails.OSType);
        }
    }

    [ControlItem[]] ApplyServiceFilters([ControlItem[]] $controls)
    {
        $result = @();
        #Check VM type
        $VMType = $this.ResourceObject.StorageProfile.OsDisk.OsType
        if($VMType -eq [Microsoft.Azure.Management.Compute.Models.OperatingSystemTypes]::Linux)
        {
            $result += $controls | Where-Object { $_.Tags -contains "Linux" };
        }
        elseif($VMType -eq [Microsoft.Azure.Management.Compute.Models.OperatingSystemTypes]::Windows)
        {
            $result += $controls | Where-Object { $_.Tags -contains "Windows" };;
        }
        if($this.VMDetails.IsVMConnectedToERvNet -and ($result | Where-Object { $_.Tags -contains "ERvNet" } | Measure-Object).Count -gt 0)
        {
            $result=$result | Where-Object { $_.Tags -contains "ERvNet" };
        }
        # Applying filter to exclude certain controls for Databricks locked RG resources
        if([Helpers]::CheckMember($this.ControlSettings, "DataBricksFilters.TagName") -and [Helpers]::CheckMember($this.ControlSettings, "DataBricksFilters.TagValue")){
            if([Helpers]::CheckMember($this.ResourceObject, "Tags") -and $this.ResourceObject.Tags[$this.ControlSettings.DataBricksFilters.TagName] -eq $this.ControlSettings.DataBricksFilters.TagValue){
                $result=$result | Where-Object { $_.Tags -notcontains "FilterDatabricks" };
            }
        }
        
        return $result;
    }

    hidden  GetVMDetails()
    {
        if($this.ResourceObject.StorageProfile.OsDisk)
        {
            $this.VMDetails.OSType = $this.ResourceObject.StorageProfile.OsDisk.OsType
        }
        else
        {
            if($this.ResourceObject.OSProfile -and $this.ResourceObject.OSProfile.LinuxConfiguration)
            {
                $this.VMDetails.OSType = [OperatingSystemTypes]::Linux
            }
            else
            {
                $this.VMDetails.OSType = [OperatingSystemTypes]::Windows
            }
        }

        if($this.ResourceObject.StorageProfile -and $this.ResourceObject.StorageProfile.ImageReference)
        {
            $this.VMDetails.Sku =  $this.ResourceObject.StorageProfile.ImageReference.Sku
            $this.VMDetails.Offer = $this.ResourceObject.StorageProfile.ImageReference.Offer
        }        
        #Get if VM is connected to ERvNet
        $this.VMDetails.IsVMConnectedToERvNet = $this.IsVMConnectedToERvNet()
        #Get VM deallocation status
        $this.VMDetails.IsVMDeallocated = $this.GetVMDeallocationStatus();
    }

    hidden [bool] IsVMConnectedToERvNet()
    {
        $IsVMConnectedToERvNet = $false
        $publicIPs = ""
        $privateIPs = ""
        $this.GetVMNICObjects() |
            ForEach-Object {         
        if($_.IpConfigurations)
                {
                    $_.IpConfigurations | 
                        ForEach-Object {
                            #Fetch Private IPs to persist in the virtual machine metadata
                            $privateIPs += $_.PrivateIpAddress + ";"
                            #Fetch Public IPs to persist in the virtual machine metadata
                            if($_.PublicIpAddress)
                            {
                                $ipResource = Get-AzResource -ResourceId $_.PublicIpAddress.Id 
                                if($ipResource)
                                {
                                    $publicIpObject = Get-AzPublicIpAddress -Name $ipResource.Name -ResourceGroupName $ipResource.ResourceGroupName
                                    if($publicIpObject)
                                    {
                                        #$_.PublicIpAddress = $publicIpObject;
                                        $publicIPs += $publicIpObject.IpAddress + ";";
                                    }
                                }
                            }
                            $subnetId = $_.Subnet.Id;        
                            $subnetName = $subnetId.Substring($subnetId.LastIndexOf("/") + 1);
                            #vnet id = trim '/subnets/' from subnet id
                            $vnetResource = Get-AzResource -ResourceId $subnetId.Substring(0, $subnetId.IndexOf("/subnets/"))

                            $vnetResource | ForEach-Object {
                                $vnet = $_
                                if($null-ne $vnet.properties -and $null -ne $vnet.properties.subnets)
                                {
                                    $vnet.properties.subnets | ForEach-Object {
                                        $subnet = $_;
                                        if($subnet.name -eq "GatewaySubnet" -and $null -ne $subnet.properties -and ([Helpers]::CheckMember($subnet.properties,"ipConfigurations")) -and ($subnet.properties.ipConfigurations | Measure-Object).Count -gt 0)
                                        {
                                            #41 number is the total character count of "Microsoft.Network/virtualNetworkGateways/"
                                            $gatewayname = $subnet.properties.ipConfigurations[0].id.Substring($subnet.properties.ipConfigurations[0].id.LastIndexOf("Microsoft.Network/virtualNetworkGateways/") + 41);
                                            $gatewayname = $gatewayname.Substring(0, $gatewayname.IndexOf("/"));

                                            $gatewayObject = Get-AzVirtualNetworkGateway -Name $gatewayname -ResourceGroupName $vnet.ResourceGroupName
                                            if( $gatewayObject.GatewayType -eq "ExpressRoute")
                                            {
                                                $IsVMConnectedToERvNet= $true
                                            }
                                        }
                                    }
                                }
                            }

                            #if($vnetResource.ResourceGroupName -in $this.ConvertToStringArray([ConfigurationManager]::GetAzSKConfigData().ERvNetResourceGroupNames))
                            #{
                            # $IsVMConnectedToERvNet= $true
                            #}
                        }
                }
            }


        $this.VMDetails.PublicIPs = $publicIPs;
        $this.VMDetails.PrivateIPs = $privateIPs;
        return $IsVMConnectedToERvNet;
    }

    hidden [bool] GetVMDeallocationStatus()
    {
        $vmStatusObj = Get-AzVM -ResourceGroupName $this.ResourceContext.ResourceGroupName -Name $this.ResourceContext.ResourceName -Status -WarningAction SilentlyContinue 
        if($vmStatusObj.Statuses -and ($vmStatusObj.Statuses | Where-Object { $_.Code.ToLower() -eq "powerState/running" }))
        {
            return $false            
        }
        else
        {
            return $true
        }
    }
     
    hidden [PSVirtualMachine] GetResourceObject()
    {
        if (-not $this.ResourceObject) {
            $this.ResourceObject = Get-AzVM -ResourceGroupName $this.ResourceContext.ResourceGroupName -Name $this.ResourceContext.ResourceName  -WarningAction SilentlyContinue 

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

        #compute ASC object for VM
        $this.ASCSettings = $this.GetASCSettings();

        if($null -ne $this.ASCSettings -and [Helpers]::CheckMember($this.ASCSettings,"properties.resourceDetails"))
        {
            $laWSSetting = $this.ASCSettings.properties.resourceDetails | Where-Object {$_.name -eq $this.ControlSettings.VirtualMachine.ASCPolicies.ResourceDetailsKeys.WorkspaceId };
            if($null -ne $laWSSetting)
            {
                $this.Workspace = $laWSSetting.value;
            }
        }

        return $this.ResourceObject;
    }

    hidden [PSObject] GetASCSettings()
    {
        $result = $null;
        # Commenting this as it's costly call and expected to happen in Set-ASC/SSS/USS
        try 
        {     
            $result = [SecurityCenterHelper]::InvokeSecurityCenterSecurityStatus($this.SubscriptionContext.SubscriptionId);
            if(($result | Measure-Object).Count -gt 0)
            {
                $key = ("$($this.ResourceContext.ResourceName):VirtualMachine").ToLower();
                $vmSecurityState = $null;
                if($result.ContainsKey($key))
                {
                    $vmSecurityState = $result[$key];
                }            
                return $vmSecurityState;            
            }            
        }
        catch
        {
            #eat exception if no ASC settings can be found
        }
        return $null;
    }

    hidden [PSNetworkInterface[]] GetVMNICObjects()
    {
        if (-not $this.VMNICs) 
        {
            $this.VMNICs = @();
            if($this.ResourceObject.NetworkProfile -and $this.ResourceObject.NetworkProfile.NetworkInterfaces)
            {
                $this.ResourceObject.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)
                            {
                                $this.VMNICs += $nicResource;
                            }
                        }
                    }
            }            
        }
        return $this.VMNICs;
    }
    
    hidden [ControlResult] CheckOSVersion([ControlResult] $controlResult)
    {

        $vmSkuDetails = $this.VMDetails | Select-Object OSType,Offer,Sku
        #in the case of classic migrated VM, we have noticed that there is no Metadata present
        if([string]::IsNullOrWhiteSpace($this.VMDetails.Offer) -or [string]::IsNullOrWhiteSpace($this.VMDetails.Sku))
        {
            $controlResult.AddMessage([VerificationResult]::Manual,"No metadata found for this VM. Verify if you are using recommended OS Sku as per Org security policy",$vmSkuDetails); 
            return     $controlResult;
        }
        $supportedSkuList = $this.VMControlSettings.SupportedSkuList | Where-Object { $_.Offer -eq $this.VMDetails.Offer } 
        if($supportedSkuList)
        {
            if($supportedSkuList.Sku -contains $this.VMDetails.Sku)
            {
                $controlResult.AddMessage([VerificationResult]::Passed,"Virtual Machine OS Sku is compliant with the Org security policy",$vmSkuDetails);                
            }
            else
            {
                $controlResult.AddMessage([VerificationResult]::Failed,"Virtual Machine OS Sku is not compliant with the Org security policy",$vmSkuDetails);                                
            }        
        }
        else
        {
            $controlResult.AddMessage([VerificationResult]::Verify,"Verify if you are using recommended OS Sku as per Org security policy",$vmSkuDetails); 
        }        
        return $controlResult;
    }

    hidden [ControlResult] CheckOSAutoUpdateStatus([ControlResult] $controlResult)
    {        
        #TCP is not applicable for Linux. #This method is deprecated
        if($this.ResourceObject.OSProfile -and $this.ResourceObject.OSProfile.WindowsConfiguration)
        {
            $message = "";
            $verificationResult = [VerificationResult]::Failed;

            if($this.ResourceObject.OSProfile.WindowsConfiguration.EnableAutomaticUpdates -eq $true)
            {
                $verificationResult = [VerificationResult]::Passed;
                $message = "Automatic OS updates are enabled on Windows Virtual Machine";
            }
            else
            {
                $message = "Automatic OS updates are disabled on Windows Virtual Machine. Please enable OS automatic updates in order to comply.";
            }

            $controlResult.AddMessage($verificationResult, $message, $this.ResourceObject.OSProfile.WindowsConfiguration);    
        
        }
        elseif($this.VMDetails.OSType -eq [OperatingSystemTypes]::Linux)
        {
            if([Helpers]::CheckMember($this.ResourceObject.OSProfile,"LinuxConfiguration")){
                $controlResult.AddMessage([VerificationResult]::Manual, "The control is not applicable in case of a Linux Virtual Machine. It's good practice to periodically update the OS of Virtual Machine.", $this.ResourceObject.OSProfile.LinuxConfiguration); 
            }
            else{
                $controlResult.AddMessage([VerificationResult]::Manual, "The control is not applicable in case of a Linux Virtual Machine. It's good practice to periodically update the OS of Virtual Machine.")
            }
        }
        else
        {
            $controlResult.AddMessage([MessageData]::new("We are not able to fetch the required data for the resource", [MessageType]::Error)); 
        }
            
        return $controlResult;
    }

    hidden [ControlResult] CheckAntimalwareStatus([ControlResult] $controlResult)
    {
        #Do not check for deallocated status for the VM and directly show the status from ASC
        if($null -ne $this.ASCSettings -and [Helpers]::CheckMember($this.ASCSettings, "properties.policyAssessments"))
        {
            $antimalwareSetting = $null
            if([FeatureFlightingManager]::GetFeatureStatus("EnableASCPolicyOnVMCheckUsingPolicyAssessmentKey",$($this.SubscriptionContext.SubscriptionId)) -eq $true)
            {
                $antimalwareSetting = $this.ASCSettings.properties.policyAssessments | Where-Object {$_.assessmentKey -eq $this.ControlSettings.VirtualMachine.ASCPolicies.PolicyAssignment.EndpointProtectionAssessmentKey};
            }
            else 
            {
                $antimalwareSetting = $this.ASCSettings.properties.policyAssessments | Where-Object {$_.policyName -eq $this.ControlSettings.VirtualMachine.ASCPolicies.PolicyAssignment.EndpointProtection};
            }

            if($null -ne $antimalwareSetting)
            {
                $controlResult.AddMessage("VM endpoint protection details:", $antimalwareSetting);
                if($antimalwareSetting.assessmentResult -eq 'Healthy' )
                {                
                    $controlResult.AddMessage([VerificationResult]::Passed,"Antimalware is configured correctly on the VM. Validated the status through ASC."); 
                }
                elseif($antimalwareSetting.assessmentResult -eq 'Low')
                {                
                    $controlResult.AddMessage([VerificationResult]::Verify,"Validate configurations of antimalware using ASC."); 
                }
                elseif($antimalwareSetting.assessmentResult -eq 'None')
                {                    
                    $controlResult.AddMessage([VerificationResult]::Manual, "The control is not applicable due to the ASC current policy."); 
                }
                else
                {                    
                    $controlResult.AddMessage([VerificationResult]::Failed,"Antimalware is not configured correctly on the VM. Validated the status through ASC."); 
                }
            }                        
        }
        else
        {
            $controlResult.AddMessage([VerificationResult]::Manual, "We are not able to check Security Center status right now. Please validate manually.");
        }
        return $controlResult;
    }

    hidden [ControlResult] CheckVulnAgentStatus([ControlResult] $controlResult)
    {
        if(-not $this.VMDetails.IsVMDeallocated)
        {
            $requiredVulnExtension = $this.VMControlSettings.VulnAssessmentSolution.AgentName
            $requiredVulnExtensionVersion =  [System.Version] $this.VMControlSettings.VulnAssessmentSolution.RequiredVersion
            if([Helpers]::CheckMember($this.ResourceObject, "Extensions")){
                $installedVulnExtension = $this.ResourceObject.Extensions | Where-Object {$_.VirtualMachineExtensionType -eq $requiredVulnExtension} 
                if($null -ne $installedVulnExtension -and $installedVulnExtension.ProvisioningState -eq "Succeeded"){
                    $currentVulnExtensionVersion = $null
                    try {
                        $ResourceAppIdURI = [WebRequestHelper]::GetResourceManagerUrl();
                        $AccessToken = [Helpers]::GetAccessToken($ResourceAppIdURI)
                        $header = "Bearer " + $AccessToken
                        $headers = @{"Authorization"=$header;"Content-Type"="application/json";}
                        $propertiesToReplace = @{}
                        $propertiesToReplace.Add("httpapplicationroutingzonename", "_httpapplicationroutingzonename")
                        $uri=[system.string]::Format("{0}subscriptions/{1}/resourceGroups/{2}/providers/Microsoft.Compute/virtualMachines/{3}/extensions/{4}?api-version=2018-06-01&`$expand=instanceView",$ResourceAppIdURI,$this.SubscriptionContext.SubscriptionId, $this.ResourceContext.ResourceGroupName, $this.ResourceContext.ResourceName,$requiredVulnExtension)
                        $result = [WebRequestHelper]::InvokeWebRequest([Microsoft.PowerShell.Commands.WebRequestMethod]::Get, $uri, $headers, $null, $null, $propertiesToReplace); 
                        $currentVulnExtensionVersion = [System.Version] $result.properties.instanceView.typeHandlerVersion
                    }
                    catch {
                        # If any exception occurs, while fetching details of Extension mark control as manual
                        $currentVulnExtensionVersion = $null
                    }
                    if($null -eq $currentVulnExtensionVersion )
                    {
                        $controlResult.AddMessage([VerificationResult]::Manual, "Not able to fetch details of vulnerability assessment extension '$($requiredVulnExtension)'.");
                    }
                    elseif($currentVulnExtensionVersion -lt $requiredVulnExtensionVersion){

                        $controlResult.AddMessage([VerificationResult]::Failed, "Vulnerability assessment solution '$($requiredVulnExtension)' is present but current verison is not latest.");
                        $controlResult.AddMessage("Current version : $($currentVulnExtensionVersion), Required version: $($requiredVulnExtensionVersion)");
                        $controlResult.SetStateData("Current version of $($requiredVulnExtension) present is:", $currentVulnExtensionVersion.ToString());
                    
                    }else{

                        $controlResult.AddMessage([VerificationResult]::Passed, "Required vulnerability assessment solution '$($requiredVulnExtension)' is present in VM.");
                    }
                }else{
                    $controlResult.AddMessage([VerificationResult]::Failed, "Required vulnerability assessment solution '$($requiredVulnExtension)' is not present in VM.");
                }
            }else{
                $controlResult.AddMessage([VerificationResult]::Failed, "Required vulnerability assessment solution '$($requiredVulnExtension)' is not present in VM.");
            }
        }
        else
        {
            $controlResult.AddMessage([VerificationResult]::Verify, "This VM is currently in a 'deallocated' state. Unable to check security controls on it.");
        }
        return $controlResult;
    }

    hidden [ControlResult] CheckGuestConfigExtension([ControlResult] $controlResult)
    {
        if(-not $this.VMDetails.IsVMDeallocated)
        {
            $guestConfigurationAssignmentName = $this.VMControlSettings.GuestExtension.AssignmentName
            $controlStatus = [VerificationResult]::Manual
            $requiredGuestExtension  = $this.VMControlSettings.GuestExtension.Name
            $requiredGuestExtensionVersion =  [System.Version] $this.VMControlSettings.GuestExtension.RequiredVersion
            $checkPolicyAssignment = $this.VMControlSettings.GuestExtension.CheckPolicyAssignment
            
            
            $ResourceAppIdURI = [WebRequestHelper]::GetResourceManagerUrl();
            $AccessToken = [Helpers]::GetAccessToken($ResourceAppIdURI)
            $header = "Bearer " + $AccessToken
            $headers = @{"Authorization"=$header;"Content-Type"="application/json";}
            $propertiesToReplace = @{}
            $propertiesToReplace.Add("httpapplicationroutingzonename", "_httpapplicationroutingzonename")

            # Check if Guest Configuration extension is present
            if([Helpers]::CheckMember($this.ResourceObject, "Extensions")){
                $installedGuestExtension = $this.ResourceObject.Extensions | Where-Object {$_.VirtualMachineExtensionType -eq $requiredGuestExtension -and $_.Publisher -eq "Microsoft.GuestConfiguration"} 
                if($null -ne $installedGuestExtension -and $installedGuestExtension.ProvisioningState -eq "Succeeded"){
                    $controlStatus = [VerificationResult]::Passed
                    $controlResult.AddMessage("Required guest configuration extension '$($requiredGuestExtension)' is present in VM.");

                    $currentGuestExtensionVersion = $null
                    try {
                        $uri=[system.string]::Format("{0}subscriptions/{1}/resourceGroups/{2}/providers/Microsoft.Compute/virtualMachines/{3}/extensions/{4}?api-version=2018-06-01&`$expand=instanceView",$ResourceAppIdURI,$this.SubscriptionContext.SubscriptionId, $this.ResourceContext.ResourceGroupName, $this.ResourceContext.ResourceName,$requiredGuestExtension)
                        $result = [WebRequestHelper]::InvokeWebRequest([Microsoft.PowerShell.Commands.WebRequestMethod]::Get, $uri, $headers, $null, $null, $propertiesToReplace); 
                        $currentGuestExtensionVersion = [System.Version] $result.properties.instanceView.typeHandlerVersion
                    }
                    catch {
                        # If any exception occurs, while fetching details of Extension mark control as manual
                        # Skip check for version
                    }
                }else{
                    $controlStatus = [VerificationResult]::Failed
                    $controlResult.AddMessage("Required guest configuration extension '$($requiredGuestExtension)' is not present in VM.");
                }
            }else{
                $controlStatus = [VerificationResult]::Failed
                $controlResult.AddMessage("Required guest configuration extension '$($requiredGuestExtension)' is not present in VM.");
            }

            # Check if reuired Guest Configuration Assignments is present
            if($checkPolicyAssignment -eq $true){
                try{
                    $uri=[system.string]::Format("{0}subscriptions/{1}/resourceGroups/{2}/providers/Microsoft.Compute/virtualMachines/{3}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments/{4}?api-version=2018-11-20",$ResourceAppIdURI,$this.SubscriptionContext.SubscriptionId, $this.ResourceContext.ResourceGroupName, $this.ResourceContext.ResourceName,$guestConfigurationAssignmentName)
                    $result = [WebRequestHelper]::InvokeWebRequest([Microsoft.PowerShell.Commands.WebRequestMethod]::Get, $uri, $headers, $null, $null, $propertiesToReplace); 
                    if($null -ne $result)
                    {    
                        $controlResult.AddMessage("Required guest configuration assignments '$($guestConfigurationAssignmentName)' is present.");
                        $controlResult.AddMessage($result);
                    
                    }
                }catch{
                    $controlStatus = [VerificationResult]::Failed
                    $controlResult.AddMessage("Required guest configuration assignments '$($guestConfigurationAssignmentName)' is not present.");    
                }
            }
        

            # Check if Managed System Identity is enabled on VM

            if([Helpers]::CheckMember($this.ResourceObject, "Identity") -and $this.ResourceObject.Identity.Type -eq "SystemAssigned"){
                $controlResult.AddMessage("SystemAssigned managed identity is enabled on VM.");
            }else{
                $controlStatus = [VerificationResult]::Failed
                $controlResult.AddMessage("The VM does not have a SystemAssigned managed identity");
            }
        }
        else
        {
            $controlStatus = [VerificationResult]::Verify
            $controlResult.AddMessage("This VM is currently in a 'deallocated' state. Unable to check security controls on it.");
        }
        $controlResult.VerificationResult = $controlStatus
        return $controlResult;
    }

    hidden [ControlResult] CheckGuestConfigPolicyStatus([ControlResult] $controlResult)
    {
        $controlStatus = [VerificationResult]::Failed
        $ResourceAppIdURI = [WebRequestHelper]::GetResourceManagerUrl();
        $AccessToken = [Helpers]::GetAccessToken($ResourceAppIdURI)
        $header = "Bearer " + $AccessToken
        $headers = @{"Authorization"=$header;"Content-Type"="application/json";}
        $propertiesToReplace = @{}
        $propertiesToReplace.Add("httpapplicationroutingzonename", "_httpapplicationroutingzonename")
        $policyAssignments = @();
        try {
                $uri=[system.string]::Format("{0}subscriptions/{1}/resourceGroups/{2}/providers/Microsoft.Compute/virtualMachines/{3}/providers/Microsoft.GuestConfiguration/guestConfigurationAssignments?api-version=2018-06-30-preview",$ResourceAppIdURI,$this.SubscriptionContext.SubscriptionId, $this.ResourceContext.ResourceGroupName, $this.ResourceContext.ResourceName)
                $response = [WebRequestHelper]::InvokeWebRequest([Microsoft.PowerShell.Commands.WebRequestMethod]::Get, $uri, $headers, $null, $null, $propertiesToReplace); 
                if($response -ne $null -and ($response|Measure-Object).Count -gt 0)
                {
                    foreach($assignment in $response){
                        if([Helpers]::CheckMember($assignment, "name") -and [Helpers]::CheckMember($assignment, "properties.complianceStatus")){
                        $assignmentObject = "" | Select-Object "assignmentName", "complianceStatus" 
                        $assignmentObject.assignmentName = $assignment.name
                        $assignmentObject.complianceStatus = $assignment.properties.complianceStatus
                        $policyAssignments += $assignmentObject
                        }

                    }
                }
                if(($policyAssignments | Measure-Object).Count -gt 0){

                    $nonCompliantPolicyAssignment = $policyAssignments | Where-Object { $_.complianceStatus -ne "Compliant"}
                    if($null -ne $nonCompliantPolicyAssignment -and ( $nonCompliantPolicyAssignment | Measure-Object).Count -gt 0 ){
                        $controlStatus = [VerificationResult]::Failed
                        $controlResult.AddMessage("For following guest configuration assignment, compliance status is 'NonCompliant' or 'Pending'.");
                        $controlResult.AddMessage($nonCompliantPolicyAssignment);
                    }else{
                        $controlStatus = [VerificationResult]::Passed
                        $controlResult.AddMessage("For all guest configuration assignment, compliance status is 'Compliant'.");
                        $controlResult.AddMessage($policyAssignments);
                    }
                    
                }else{
                    $controlStatus = [VerificationResult]::Verify
                    $controlResult.AddMessage("No guest configuration policy assignment found.");
                }
            }
            catch {

                $controlStatus = [VerificationResult]::Verify
                $controlResult.AddMessage("Not able to fetch guest configuration policy assignments details.");
            }
        
        $controlResult.VerificationResult = $controlStatus
        return $controlResult;
    }

    hidden [ControlResult] CheckNSGConfig([ControlResult] $controlResult)
    {
        $controlResult.VerificationResult = [VerificationResult]::Failed;
        $this.GetVMNICObjects() |
            ForEach-Object {          
                #Check NSGs applied at NIC level
                if($_.NetworkSecurityGroup)
                {
                    if($_.NetworkSecurityGroup.SecurityRules.Count -gt 0)
                    {
                        $controlResult.AddMessage("Validate NSG security rules applied to NIC - [$($_.Name)], Total - $($_.NetworkSecurityGroup.SecurityRules.Count)", $_.NetworkSecurityGroup.SecurityRules);              
                    }
                    if($_.NetworkSecurityGroup.DefaultSecurityRules.Count -gt 0)
                    {
                        $controlResult.AddMessage("Validate default NSG security rules applied to NIC - [$($_.Name)], Total - $($_.NetworkSecurityGroup.DefaultSecurityRules.Count)", $_.NetworkSecurityGroup.DefaultSecurityRules); 
                    }
                    $controlResult.VerificationResult = [VerificationResult]::Verify;
                    $controlResult.SetStateData("NSG security rules", $_.NetworkSecurityGroup.SecurityRules);
                }  
            
                #check NSGs applied at subnet level
                if($_.IpConfigurations)
                {
                    $_.IpConfigurations | 
                        ForEach-Object {                   
                            $subnetId = $_.Subnet.Id;        
                            $subnetName = $subnetId.Substring($subnetId.LastIndexOf("/") + 1);
                            #vnet id = trim '/subnets/' from subnet id
                            $vnetResource = Get-AzResource -ResourceId $subnetId.Substring(0, $subnetId.IndexOf("/subnets/"))
                            if($vnetResource)
                            {
                                $vnetObject = Get-AzVirtualNetwork -Name $vnetResource.Name -ResourceGroupName $vnetResource.ResourceGroupName
                                if($vnetObject)
                                {
                                    $subnetConfig = Get-AzVirtualNetworkSubnetConfig -Name $subnetName -VirtualNetwork $vnetObject
                                    if($subnetConfig -and $subnetConfig.NetworkSecurityGroup -and $subnetConfig.NetworkSecurityGroup.Id)
                                    {
                                        $nsgResource = Get-AzResource -ResourceId $subnetConfig.NetworkSecurityGroup.Id
                                        if($nsgResource)
                                        {
                                            $nsgObject = Get-AzNetworkSecurityGroup -Name $nsgResource.Name -ResourceGroupName $nsgResource.ResourceGroupName
                                            if($nsgObject)
                                            {
                                                if($nsgObject.SecurityRules.Count -gt 0)
                                                {
                                                    $controlResult.AddMessage("Validate NSG security rules applied to Subnet - [$subnetName] in Virtual Network - [$($vnetResource.Name)]. Total - $($nsgObject.SecurityRules.Count)", $nsgObject.SecurityRules);                                       
                                                }
                                                
                                                if($nsgObject.DefaultSecurityRules.Count -gt 0)
                                                {
                                                    $controlResult.AddMessage("Validate default NSG security rules applied to Subnet - [$subnetName] in Virtual Network - [$($vnetResource.Name)]. Total - $($nsgObject.DefaultSecurityRules.Count)", $nsgObject.DefaultSecurityRules);
                                                }
                                                $controlResult.VerificationResult = [VerificationResult]::Verify;
                                                $controlResult.SetStateData("NSG security rules", $nsgObject.SecurityRules);
                                            }
                                        }
                                    }
                                }
                            }
                        }           
                }            
            }
        if($this.VMDetails.IsVMConnectedToERvNet)
        {
            $controlResult.AddMessage("This VM is part of an ExpressRoute connected virtual network.")    
        }
        if($controlResult.VerificationResult -ne [VerificationResult]::Verify -and $this.VMDetails.IsVMConnectedToERvNet)
        {            
            $controlResult.AddMessage("No NSG was found on Virtual Machine subnet or NIC.")    
            $controlResult.VerificationResult = [VerificationResult]::Passed;
        }
        elseif($controlResult.VerificationResult -ne [VerificationResult]::Verify)
        {
            $controlResult.AddMessage("No NSG was found on Virtual Machine subnet or NIC.")        
        }
        return $controlResult;
    }

    hidden [ControlResult] CheckPublicIP([ControlResult] $controlResult)
    {    
        $publicIps = @();
        $this.GetVMNICObjects() | 
            ForEach-Object {
                $_.IpConfigurations | Where-Object { $_.PublicIpAddress } |
                    ForEach-Object {
                        $ipResource = Get-AzResource -ResourceId $_.PublicIpAddress.Id 
                        if($ipResource)
                        {
                            $publicIpObject = Get-AzPublicIpAddress -Name $ipResource.Name -ResourceGroupName $ipResource.ResourceGroupName
                            if($publicIpObject)
                            {
                                $_.PublicIpAddress = $publicIpObject;
                                $publicIps += $publicIpObject;
                            }
                        }
                    }
            }
         
        if($this.VMDetails.IsVMConnectedToERvNet)
        {
            $controlResult.AddMessage("This VM is part of an ExpressRoute connected virtual network. You must not have any Public IP assigned to such VM. ");
        }
        if($publicIps.Count -gt 0 -and $this.VMDetails.IsVMConnectedToERvNet)
        {              
            $controlResult.AddMessage([VerificationResult]::Failed, "Total Public IPs Found- $($publicIps.Count)", $publicIps);  
            $controlResult.SetStateData("Public IP(s) associated with Virtual Machine", $publicIps);
        }
        elseif($publicIps.Count -gt 0)
        {
            $controlResult.AddMessage([VerificationResult]::Verify, "Validate Public IP(s) associated with Virtual Machine. Total - $($publicIps.Count)", $publicIps);  
            $controlResult.SetStateData("Public IP(s) associated with Virtual Machine", $publicIps);
        }
        else
        {
            $controlResult.AddMessage([VerificationResult]::Passed, "No Public IP is associated with Virtual Machine");
        }
        return $controlResult;
    }

    hidden [ControlResult] CheckDiskEncryption([ControlResult] $controlResult)
    {    
        #Do not check for deallocated status for the VM and directly show the status from ASC
        $ascDiskEncryptionStatus = $false;

        if($null -ne $this.ASCSettings -and [Helpers]::CheckMember($this.ASCSettings, "properties.policyAssessments"))
        {
            $adeSetting = $null
            if([FeatureFlightingManager]::GetFeatureStatus("EnableASCPolicyOnVMCheckUsingPolicyAssessmentKey",$($this.SubscriptionContext.SubscriptionId)) -eq $true)
            {
                $adeSetting = $this.ASCSettings.properties.policyAssessments | Where-Object {$_.assessmentKey -eq $this.ControlSettings.VirtualMachine.ASCPolicies.PolicyAssignment.DiskEncryptionAssessmentKey};
            }
            else 
            {
                $adeSetting = $this.ASCSettings.properties.policyAssessments | Where-Object {$_.policyName -eq $this.ControlSettings.VirtualMachine.ASCPolicies.PolicyAssignment.DiskEncryption};
            }

            if($null -ne $adeSetting)
            {
                if($adeSetting.assessmentResult -eq 'Healthy')
                {
                    $ascDiskEncryptionStatus = $true;
                }
            }
            $controlResult.AddMessage("VM disk encryption details:", $adeSetting);
        }                
                
        if($ascDiskEncryptionStatus)
        {
            $verificationResult  = [VerificationResult]::Passed;
            $message = "All Virtual Machine disks (OS and Data disks) are encrypted. Validated the status through ASC.";
            $controlResult.AddMessage($verificationResult, $message);
        }
        else
        {            
            $verificationResult  = [VerificationResult]::Failed;
            $message = "All Virtual Machine disks (OS and Data disks) are not encrypted. Validated the status through ASC.";
            $controlResult.AddMessage($verificationResult, $message);
        }
        return $controlResult;
    }

    hidden [ControlResult] CheckASCStatus([ControlResult] $controlResult)
    {
        #This is deprecated method. Commented the code below
        #$isManual = $false;
        # if($this.ASCSettings)
        # {
        # if($this.ASCSettings.SecurityState -ne 'Healthy')
        # {
        # $controlResult.VerificationResult = [VerificationResult]::Failed

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

        # $controlResult.AddMessage("Security Center status for Virtual Machine [$($this.ResourceContext.ResourceName)] is: [$($this.ASCSettings.SecurityState)]", $this.ASCSettings);
        # $controlResult.SetStateData("Security Center status for Virtual Machine", $this.ASCSettings);
        # }
        # else
        # {
        # $isManual = $true;
        # }

        # if($isManual)
           # {
        # $controlResult.AddMessage([VerificationResult]::Manual, "We are not able to check Security Center status right now. Please validate manually.");
        # }

         return $controlResult;
    }

    #No contol found with this method name
    hidden [ControlResult] CheckASCVulnerabilities([ControlResult] $controlResult)
    {
        $ascVMVulnerabilitiesStatusHealthy = $false;

        if($null -ne $this.ASCSettings -and [Helpers]::CheckMember($this.ASCSettings, "properties.policyAssessments"))
        {
            $vulnSetting = $null
            if([FeatureFlightingManager]::GetFeatureStatus("EnableASCPolicyOnVMCheckUsingPolicyAssessmentKey",$($this.SubscriptionContext.SubscriptionId)) -eq $true)
            {
                $vulnSetting = $this.ASCSettings.properties.policyAssessments | Where-Object {$_.assessmentKey -eq $this.ControlSettings.VirtualMachine.ASCPolicies.PolicyAssignment.VulnerabilityScanAssessmentKey};
            }
            else 
            {
                $vulnSetting = $this.ASCSettings.properties.policyAssessments | Where-Object {$_.policyName -eq $this.ControlSettings.VirtualMachine.ASCPolicies.PolicyAssignment.VulnerabilityScan};
            }

            if($null -ne $vulnSetting)
            {
                if($vulnSetting.assessmentResult -eq 'Healthy')
                {
                    $ascVMVulnerabilitiesStatusHealthy = $true;
                }
            }
            $controlResult.AddMessage("VM vuln scan details:", $vulnSetting);
        }            
        
        if($ascVMVulnerabilitiesStatusHealthy)
        {
            $controlResult.VerificationResult = [VerificationResult]::Passed

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

        $controlResult.AddMessage("Security Center VM Vulnerability status for Virtual Machine [$($this.ResourceContext.ResourceName)]", $ascVMVulnerabilitiesStatusHealthy);        

        return $controlResult;
    }

    hidden [ControlResult] CheckASCVMMissingPatchingStatus([ControlResult] $controlResult)
    {
        #Do not check for deallocated status for the VM and directly show the status from ASC
        $isVerify = $false;
        $ASCApprovedPatchStatus=$this.VMControlSettings.ASCApprovedPatchingHealthStatuses;
        #Get VM ASC Setting
        $ASCSettingsforVM=$this.ASCSettings;
        if($null -ne $ASCSettingsforVM)
        {
                # workspace associated by ASC to send logs for this VM
                $workspaceId=$this.Workspace;
                $queryforPatchDetails=[string]::Format($this.VMControlSettings.QueryforMissingPatches,($this.ResourceContext.ResourceId).ToLower());               

                $ascPatchStatus = "";

                if($null -ne $this.ASCSettings -and [Helpers]::CheckMember($this.ASCSettings, "properties.policyAssessments"))
                {
                    $patchSetting = $null
                    if([FeatureFlightingManager]::GetFeatureStatus("EnableASCPolicyOnVMCheckUsingPolicyAssessmentKey",$($this.SubscriptionContext.SubscriptionId)) -eq $true)
                    {
                        $patchSetting = $this.ASCSettings.properties.policyAssessments | Where-Object {$_.assessmentKey -eq $this.ControlSettings.VirtualMachine.ASCPolicies.PolicyAssignment.OSUpdatesAssessmentKey};
                    }
                    else 
                    {
                        $patchSetting = $this.ASCSettings.properties.policyAssessments | Where-Object {$_.policyName -eq $this.ControlSettings.VirtualMachine.ASCPolicies.PolicyAssignment.OSUpdates};
                    }

                    if($null -ne $patchSetting)
                    {
                        $ascPatchStatus = $patchSetting.assessmentResult;
                    }
                    $controlResult.AddMessage("VM patch status details:", $patchSetting);
                }        
                
                if($ascPatchStatus -in $ASCApprovedPatchStatus)
                {
                    $controlResult.VerificationResult = [VerificationResult]::Passed    
                }
                else
                {
                    $controlResult.VerificationResult=[VerificationResult]::Verify;
                    $controlResult.AddMessage("Details of missing patches can be obtained from the following workspace");
                    $controlResult.AddMessage("Workspace : ",$workspaceId);
                    $controlResult.AddMessage("The following query can be used to obtain patch details:");
                    $controlResult.AddMessage("Query : ",$queryforPatchDetails);
                }                
        }
        else
        {
            $controlResult.AddMessage([VerificationResult]::Manual, "We are not able to check Security Center status right now. Please validate manually.");
        }
      return $controlResult;
    }

    hidden [ControlResult] CheckASCVMRecommendations([ControlResult] $controlResult)
    {

        $isManual = $false;
        $result = $null 
        
        $activeRecommendations = @()
        $ASCWhitelistedRecommendations = @();
        $ASCWhitelistedRecommendations += $this.VMControlSettings.ASCRecommendations;
        #[Helpers]::RegisterResourceProviderIfNotRegistered([SecurityCenterHelper]::ProviderNamespace);
        $tasks = [SecurityCenterHelper]::InvokeGetASCTasks($this.SubscriptionContext.SubscriptionId);
        $found = $false;
        if($null -ne $ASCWhitelistedRecommendations -and $null -ne $tasks)
        {
            $tasks | ForEach-Object {
                $recommendation = $_;
                if(($ASCWhitelistedRecommendations | Where-Object { $_ -eq $recommendation.Name -and `
                                                                            $recommendation.State -eq "Active" -and`
                                                                            $recommendation.ResourceId -eq $this.ResourceContext.ResourceId} | Measure-Object).Count -gt 0)
                {
                    $found = $true;
                    $activeRecommendations += $_;
                }
            }
        }
        elseif($null -ne $tasks -and ($tasks | Where-Object { $_.State -eq "Active" -and $_.ResourceId -eq $this.ResourceContext.ResourceId} | Measure-Object).Count -gt 0)
        {
            $found = $true;
            $activeRecommendations = $tasks | Where-Object { $_.State -eq "Active" -and $_.ResourceId -eq $this.ResourceContext.ResourceId} 
        }

        if($found)
        {
            $controlResult.SetStateData("Active recommendations in Security Center", $activeRecommendations);
            $controlResult.AddMessage([VerificationResult]::Failed,"Azure Security Center has active recommendations that need to resolved.")
        }
        else {
            $controlResult.VerificationResult =[VerificationResult]::Passed
        }

        $controlResult.AddMessage(($activeRecommendations | Select-Object Name, State, ResourceId));

        return $controlResult
    }

    hidden [ControlResult] CheckASCVMSecurityBaselineStatus([ControlResult] $controlResult)
    {
        
        $isVerfiy= $false;
        $baselineIds = @();
        $baselineIds += $this.VMControlSettings.BaselineIds
        $queryforFailingBaseline=[string]::Format($this.VMControlSettings.QueryforBaselineRule,($this.ResourceContext.ResourceId).ToLower());
        $ASCApprovedStatuses=$this.VMControlSettings.ASCApprovedBaselineStatuses
        # Get ASC Settings for the VM
        $ASCSettingsforVM=$this.ASCSettings;

        if($null -ne $ASCSettingsforVM)
        {
            # workspace associated by ASC to send logs for this VM
            $workspaceId=$this.Workspace;
            $vulnStatus = "";

            if($null -ne $this.ASCSettings -and [Helpers]::CheckMember($this.ASCSettings, "properties.policyAssessments"))
            {
                $vulnSetting = $null
                if([FeatureFlightingManager]::GetFeatureStatus("EnableASCPolicyOnVMCheckUsingPolicyAssessmentKey",$($this.SubscriptionContext.SubscriptionId)) -eq $true)
                {
                    $vulnSetting = $this.ASCSettings.properties.policyAssessments | Where-Object {$_.assessmentKey -eq $this.ControlSettings.VirtualMachine.ASCPolicies.PolicyAssignment.VulnerabilityScanAssessmentKey};
                }
                else 
                {
                    $vulnSetting = $this.ASCSettings.properties.policyAssessments | Where-Object {$_.policyName -eq $this.ControlSettings.VirtualMachine.ASCPolicies.PolicyAssignment.VulnerabilityScan};
                }

                if($null -ne $vulnSetting)
                {
                    $vulnStatus = $vulnSetting.assessmentResult;
                }
                $controlResult.AddMessage("VM patch status details:", $vulnSetting);
            }        

            if($vulnStatus -in  $ASCApprovedStatuses)
            {
                $controlResult.VerificationResult = [VerificationResult]::Passed
            }
            else
            {
                $controlResult.VerificationResult = [VerificationResult]::Verify
                $controlResult.AddMessage("Unable to validate baseline status from workspace.Please verify.");
                $controlResult.AddMessage("Details of failing baseline rules can be obtained from Log Analytics workspace :" ,$workspaceId);
                $controlResult.AddMessage("The following query can be used to obtain failing baseline rules : ",$queryforFailingBaseline);
            }
        }
        else
        {
            $controlResult.AddMessage([VerificationResult]::Manual, "We are not able to check Security Center status right now. Please validate manually.");
        }
        return $controlResult;
    }
    
    hidden [ControlResult] CheckVMDiagnostics([ControlResult] $controlResult)
    {        
        if($this.ResourceObject.Extensions)
        {
            $diagnosticExtensionType = if($this.VMDetails.OSType -eq [OperatingSystemTypes]::Linux) { "LinuxDiagnostic" } else { "IaaSDiagnostics" }
            
            $diagExtension = $this.ResourceObject.Extensions | Where-Object { $_.VirtualMachineExtensionType -eq $diagnosticExtensionType } | Select-Object -First 1
            if($diagExtension -and ($diagExtension.ProvisioningState -eq "Succeeded"))
            {
                $controlResult.AddMessage([VerificationResult]::Passed, "'$diagnosticExtensionType' extension is installed on Virtual Machine");
            }
            else
            {
                $controlResult.AddMessage([VerificationResult]::Failed, "'$diagnosticExtensionType' extension is either not installed or provisioning failed on Virtual Machine");
            }
        }
        else
        {
            $controlResult.AddMessage([MessageData]::new("We are not able to fetch the required data for the resource", [MessageType]::Error)); 
        }

        return $controlResult;
    }

    hidden [ControlResult] CheckOpenPorts([ControlResult] $controlResult)
    {    
        if(-not $this.VMDetails.IsVMDeallocated)
        {
            
            $isManual = $false
            $controlResult.AddMessage("Checking for Virtual Machine management ports",$this.VMControlSettings.ManagementPortList);
            $vulnerableNSGsWithRules = @();
            $effectiveNSG = $null;
            $openPortsList =@();
            $this.GetVMNICObjects() | 
                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 -or $statusCode -eq [System.Net.HttpStatusCode]::Conflict)
                        {                            
                            $controlResult.AddMessage(($_.Exception).InnerException.Message);    
                        }
                        # else
                        # {
                        # throw $_
                        # }
                    }
                if($effectiveNSG)
                    {
                        $vulnerableRules = @()
                        
                        if($this.VMControlSettings -and $this.VMControlSettings.ManagementPortList)
                        {
                            Foreach($PortDetails in  $this.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, "We are not able 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 Virtual Machine. 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, "VM is part of ER Network. And no NSG found for Virtual Machine");  
                }
                else
                {
                    $controlResult.AddMessage([VerificationResult]::Failed, "Verify if NSG is attached to 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 Virtual Machine");  
                }
                else
                {
                    $controlResult.AddMessage("List of open ports: ",$openPortsList);
                    $controlResult.AddMessage([VerificationResult]::Verify, "Management ports are open on Virtual Machine. Please verify and remove the NSG rules in order to comply.", $vulnerableNSGsWithRules);

                    $controlResult.SetStateData("Management ports list on Virtual Machine", $vulnerableNSGsWithRules);
                }
            }        
        }
        else
        {
            $controlResult.AddMessage([VerificationResult]::Verify, "This VM is currently in a 'deallocated' state. Unable to check security controls on it.");
        }
        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;
    }
}


Class VMDetails{
[OperatingSystemTypes] $OSType
[string] $Offer
[string] $Sku
[bool] $IsVMConnectedToERvNet
[bool] $IsVMDeallocated
[string] $PublicIPs
[string] $PrivateIPs
}