Framework/Core/SubscriptionSecurity/Alerts.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
using namespace System.Management.Automation
Set-StrictMode -Version Latest 

# Class to implement Subscription alert controls
class Alerts: CommandBase
{    
    hidden [PSObject[]] $Policy = $null;
    
    hidden [PSObject[]] $ApplicableAlerts = $null;
    
    hidden [string] $TargetResourceGroup;
    hidden [string] $ResourceGroup ;
    hidden [string] $ResourceGroupLocation;
    hidden [PSObject] $AlertPolicyObj = $null
    hidden [string] $V1AlertRGName;
    hidden [string] $RunbookName=[Constants]::AlertRunbookName
    hidden [string] $AutomationWebhookName=[Constants]::AutomationWebhookName
    hidden [string] $AutomationAccountName=[Constants]::AutomationAccountName
    hidden [int] $WebhookExpiryInDays = [Constants]::AlertWebhookUriExpiryInDays
    Alerts([string] $subscriptionId, [InvocationInfo] $invocationContext, [string] $tags): 
        Base($subscriptionId, $invocationContext)
    {
        $this.V1AlertRGName = [OldConstants]::V1AlertRGName
        $this.ResourceGroup = [ConfigurationManager]::GetAzSKConfigData().AzSKRGName
        $this.AlertPolicyObj =  $this.LoadServerConfigFile("Subscription.InsARMAlerts.json");
        $this.FilterTags = $this.ConvertToStringArray($tags);
        $this.ResourceGroupLocation = [ConfigurationManager]::GetAzSKConfigData().AzSKLocation;
        $this.Policy = $this.AlertPolicyObj.AlertList 
    }

    hidden [PSObject[]] GetApplicableAlerts([string[]] $alertNames)
    {
        if($null -eq $this.ApplicableAlerts)
        {
            $this.ApplicableAlerts = @();

            if($alertNames -and $alertNames.Count -ne 0)
            {
                $this.ApplicableAlerts += $this.Policy | Where-Object { $alertNames -Contains $_.Name };
            }
            elseif(($this.FilterTags | Measure-Object).Count -ne 0)
            {
                $this.Policy |
                    ForEach-Object {
                        $currentResourceTypeItem = $_;
                        $applicableAlert = @{ Name=$currentResourceTypeItem.Name;Description = $currentResourceTypeItem.Description; OperationNameList =@(); Enabled = $currentResourceTypeItem.Enabled }
                        $currentResourceTypeItem.AlertOperationList | ForEach-Object{
                        $currentItem = $_                            
                        if(($currentItem | Where-Object { $this.FilterTags -Contains $_.Tags  -and $_.Enabled -eq $true} | Measure-Object).Count -ne 0)
                        {
                            $applicableAlert.OperationNameList  += $currentItem.OperationName;
                        }

                    }
                        if(($applicableAlert.OperationNameList | Measure-Object).Count -gt 0 )
                        {
                            $this.ApplicableAlerts += $applicableAlert
                        }
                    }
            }
        }
            
        return $this.ApplicableAlerts;
    }
    hidden [PSObject[]] GetApplicableAlerts()
    {
        return $this.GetApplicableAlerts(@());
    }

    [MessageData[]] RemoveAlerts([string] $alertNames, [bool] $DeleteActionGroup)
    {
        return $this.RemoveAlerts($this.ResourceGroup, $alertNames, $DeleteActionGroup)
    }

    [MessageData[]] RemoveAlerts([string] $rgName,  [string] $alertNames, [bool] $DeleteActionGroup)
    {
        [MessageData[]] $messages = @();

        # Check for existence of resource group

        $existingRG = Get-AzureRmResourceGroup -Name $rgName -ErrorAction SilentlyContinue
        if($existingRG)
        {
            $startMessage = [MessageData]::new("Found alerts resource group: $rgName");
            $messages += $startMessage;
            $this.PublishCustomMessage($startMessage);

            $alertNameArray = @();        
            if(-not [string]::IsNullOrWhiteSpace($alertNames))
            {
                $alertNameArray += $this.ConvertToStringArray($alertNames);
                if($alertNameArray.Count -eq 0)
                {
                    throw ([SuppressedException]::new(("The argument 'alertNames' is null or empty"), [SuppressedExceptionType]::NullArgument))
                }
            }        
            $policyList=@();
            ForEach($Tag in $this.FilterTags)
            {
              $policyList+= $this.Policy | where{ $Tag -In $_.Tags }
            }    
            $this.Policy=$policyList| Select-Object * -Unique    
            $this.Policy |ForEach-Object {
                           $alertNameArray+=$_.Name }

            # User wants to remove only specific alerts
            if(($this.Policy | Measure-Object).Count -ne 0)
            {
                if($this.GetApplicableAlerts($alertNameArray) -ne 0)
                {
                    $startMessage = [MessageData]::new("Removing alerts. Tags:[$([string]::Join(",", $this.FilterTags))]. Total alerts: $($this.GetApplicableAlerts($alertNameArray).Count)");
                    $messages += $startMessage;
                    $this.PublishCustomMessage($startMessage);
                    $this.PublishCustomMessage("Note: Removing alerts can take few minutes depending on number of alerts to be processed...", [MessageType]::Warning);                

                    $disabledAlerts = $this.GetApplicableAlerts($alertNameArray) | Where-Object { -not $_.Enabled };
                    if(($disabledAlerts | Measure-Object).Count -ne 0)
                    {
                        $disabledMessage = "Found alerts which are disabled and will not be removed. This is intentional. Total disabled alerts: $($disabledAlerts.Count)";
                        $messages += [MessageData]::new($disabledMessage, $disabledAlerts);
                        #$this.PublishCustomMessage($disabledMessage, [MessageType]::Warning);
                    }

                    $enabledAlerts = @();
                    $enabledAlerts += $this.GetApplicableAlerts($alertNameArray) | Where-Object { $_.Enabled };
                    if($enabledAlerts.Count -ne 0)
                    {
                        $messages += [MessageData]::new([Constants]::SingleDashLine + "`r`nRemoving following alerts from the subscription. Total alerts: $($enabledAlerts.Count)", $enabledAlerts);                                            

                        $errorCount = 0;
                        $currentCount = 0;
                        $enabledAlerts | ForEach-Object {
                            $alertName = $_.Name;
                            $currentCount += 1;
                            # Remove alert
                            try
                            {
                                Remove-AzureRmResource -ResourceType "Microsoft.Insights/activityLogAlerts" -ResourceGroupName  $rgName -Name $alertName -Force
                                #Remove-AzureRmAlertRule -ResourceGroup $this.ResourceGroup -Name $alertName -WarningAction SilentlyContinue
                            }
                            catch
                            {
                                $messages += [MessageData]::new("Error while removing alert [$alertName] from the subscription", $_, [MessageType]::Error);
                                $errorCount += 1;
                            }

                            $this.CommandProgress($enabledAlerts.Count, $currentCount, 20);
                        };

                        [MessageData[]] $resultMessages = @();
                        if($errorCount -eq 0)
                        {
                            #setting the tag at AzSKRG
                            [Helpers]::SetResourceGroupTags($rgName,@{[Constants]::AzSKAlertsVersionTagName=$this.AlertPolicyObj.Version}, $true)

                            $resultMessages += [MessageData]::new("All alerts have been removed from the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
                            if($DeleteActionGroup)
                            {
                                Remove-AzureRmResource -ResourceType "Microsoft.Insights/actiongroups" -ResourceGroupName $rgName -Name $([Constants]::AlertActionGroupName) -Force
                                Remove-AzureRmResource -ResourceType "Microsoft.Insights/actiongroups" -ResourceGroupName $rgName -Name $([Constants]::CriticalAlertActionGroupName) -ErrorAction SilentlyContinue -Force 
                                $resultMessages += [MessageData]::new("Action Group have been removed from the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
                            }
                                
                        }
                        elseif($errorCount -eq $enabledAlerts.Count)
                        {
                            $resultMessages += [MessageData]::new("No alerts have been removed from the subscription due to error occurred. Please add the alerts manually.`r`n" + [Constants]::SingleDashLine, [MessageType]::Error);
                        }
                        else
                        {
                            $resultMessages += [MessageData]::new("$errorCount/$($enabledAlerts.Count) alert(s) have not been removed from the subscription. Please remove the alerts manually.", [MessageType]::Error);
                            $resultMessages += [MessageData]::new("$($enabledAlerts.Count - $errorCount)/$($enabledAlerts.Count) alert(s) have been removed from the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
                        }
                        $messages += $resultMessages;
                        $this.PublishCustomMessage($resultMessages);

                        #Remove Old alerts

                        #$curActionGroup = $this.GetAlertActionGroupId([OldConstants]::AzSDKRGName);
                        #if($curActionGroup)
                        #{
                        # Find-AzureRmResource -ResourceGroupNameEquals $([OldConstants]::AzSDKRGName) -ResourceType "Microsoft.Insights/activityLogAlerts" -ErrorAction SilentlyContinue | Remove-AzureRmResource -Force -ErrorAction SilentlyContinue
                        # Find-AzureRmResource -ResourceGroupName $([OldConstants]::AzSDKRGName) -ResourceType "Microsoft.Insights/actiongroups" -ErrorAction SilentlyContinue | Remove-AzureRmResource -Force -ErrorAction SilentlyContinue
                        #}

                    }
                }
                else
                {
                    $this.PublishCustomMessage("No alerts have been found that matches the specified tags. Tags:[$([string]::Join(",", $this.FilterTags))].", [MessageType]::Warning);
                }
            }
            else
            {
                $this.PublishCustomMessage("No alerts found in the alert policy file", [MessageType]::Warning);
            }
        }
        else
        {
            $this.PublishCustomMessage("No configured alerts found in the subscription. Resource group not found: $rgName", [MessageType]::Warning);
        }
        return $messages;
    }    

    [MessageData[]] SetAlerts([string] $targetResourceGroup, [string] $securityContactEmails,[string] $SecurityPhoneNumbers, [string] $alertResourceGroupLocation, [PSObject] $emailReceivers, [PSObject] $smsReceivers, [string] $curWebhookUri)
    {
        $actionGroupResourceId = $null
        $criticalAlertActionGroupResourceId=$null
        $existingWebhookUri=$null
        [MessageData[]] $messages = @();
        $webhookUri = $curWebhookUri;
        #There is a possibility that if the Alerts are reconfigured, the existing webhook uri will get overwritten with the new setup. Need to take the current backup
        if([string]::IsNullOrWhiteSpace($webhookUri))
        {
            $webhookUri = $this.ComputeAlertRunbookWebhookUri();
        }        

        if(-not [string]::IsNullOrWhiteSpace($SecurityPhoneNumbers) -or $smsReceivers -ne $null)
        {
            if(-not $this.FilterTags.Contains("SMS"))
            {
                $this.FilterTags += "SMS"
            }
        }

        if($this.Force -or -not ($this.IsLatestVersionConfiguredOnSub($this.AlertPolicyObj.Version,[Constants]::AzSKAlertsVersionTagName,"Alerts")))
        {
            $allEmails = @();
            # Parameter validation
            if([string]::IsNullOrWhiteSpace($securityContactEmails))
            {
                #If security contact emails is blank check if old V1 alerts are configured and get email from alert resource
                #Check if V2 alert action group is present and assign existing action group resource Id
                $actionGroupResourceId = "";
                $curActionGroup = $this.GetAlertActionGroup($this.ResourceGroup, [Constants]::AlertActionGroupName)
                if($curActionGroup)
                {
                    $actionGroupResourceId = $curActionGroup.ResourceId
                }

                $criticalAlertActionGroupResourceId = "";
                $curCriticalActionGroup = $this.GetAlertActionGroup($this.ResourceGroup, [Constants]::CriticalAlertActionGroupName)
                if($curCriticalActionGroup)
                {
                    $criticalAlertActionGroupResourceId = $curCriticalActionGroup.ResourceId
                }

                if(($curActionGroup | Measure-Object).Count -eq 0 -and $emailReceivers -eq $null)
                {
                    $this.PublishCustomMessage("'SecurityContactEmails' is required to configure alerts. Please set up alerts with cmdlet Set-AzSKAlerts. Run 'Get-Help Set-AzSKAlerts -full' for more help.", [MessageType]::Error);
                    return $null;
                }            
            }
            else
            {
                $allEmails += $this.ConvertToStringArray($securityContactEmails);
                #Validate emails
                if((($allEmails | Measure-Object).Count -gt 0))
                {
                    $invalidEmailList = [Helpers]::ValidateEmailList($allEmails)
                    if(($invalidEmailList| Measure-Object).Count -gt 0)
                    {
                         $this.PublishCustomMessage(("Please enter valid security contact email id(s): "+ [string]::Join(",", $invalidEmailList)) , [MessageType]::Error);
                         return $null
                    }            
                }
            }


            if(-not [string]::IsNullOrWhiteSpace($alertResourceGroupLocation))
            {
                $this.ResourceGroupLocation = $alertResourceGroupLocation;
            }

        
            if(($this.Policy | Measure-Object).Count -ne 0)
            {
                $alertList = $this.GetApplicableAlerts();
                if($alertList -ne 0)
                {
                    $criticalAlerts = $alertList 
                    $startMessage = [MessageData]::new("Processing AzSK alerts. Total alert groups: $($criticalAlerts.Count)");
                    $messages += $startMessage;
                    $this.PublishCustomMessage($startMessage);
                    $this.PublishCustomMessage("Note: Configuring alerts can take about 4-5 min...", [MessageType]::Warning);                

                    $disabledAlerts = $criticalAlerts | Where-Object { -not $_.Enabled };
                    if(($disabledAlerts | Measure-Object).Count -ne 0)
                    {
                        $disabledMessage = "Found alerts which are disabled. This is intentional. Total disabled alerts: $($disabledAlerts.Count)";
                        $messages += [MessageData]::new($disabledMessage, $disabledAlerts);                    
                    }

                    $enabledAlerts = @();
                    $enabledAlerts += $criticalAlerts | Where-Object { $_.Enabled };
                    if($enabledAlerts.Count -ne 0)
                    {
                        $messages += [MessageData]::new([Constants]::SingleDashLine + "`r`nAdding following alerts to the subscription. Total alerts: $($enabledAlerts.Count)", $enabledAlerts);                                            

                        # Check if Resource Group exists
                        $existingRG = Get-AzureRmResourceGroup -Name $this.ResourceGroup -ErrorAction SilentlyContinue
                        if(-not $existingRG)
                        {
                            [Helpers]::NewAzSKResourceGroup($this.ResourceGroup,$this.ResourceGroupLocation,$this.GetCurrentModuleVersion())                        
                        }
                        $messages += [MessageData]::new("All the alerts registered by this script will be placed in a resource group named: $($this.ResourceGroup)");
                        $isTargetResourceGroup = -not [string]::IsNullOrWhiteSpace($targetResourceGroup);
                        #if email address are provided, Create/edit the action group. This will not support append functionality.
                        if(($allEmails | Measure-Object).Count -gt 0 -or $emailReceivers -ne $null)
                        {
                            $actionGroupResourceId = $this.SetupAlertActionGroup($allEmails,$SecurityPhoneNumbers,$emailReceivers)                        
                            if([string]::IsNullOrWhiteSpace($actionGroupResourceId))
                            {
                                $this.PublishCustomMessage("Not able to create alert action group. Validate detailed log for more details.", [MessageType]::Error);
                                return $messages
                            }
                            if(-not [string]::IsNullOrWhiteSpace($SecurityPhoneNumbers) -or $smsReceivers -ne $null)
                            {
                                $criticalAlertActionGroupResourceId = $this.SetupAlertActionGroup($SecurityPhoneNumbers, $smsReceivers)
                                if([string]::IsNullOrWhiteSpace($criticalAlertActionGroupResourceId))
                                {
                                     $this.PublishCustomMessage("Could not register SMS alerts for some very critical actions. Please rerun the command with a correct country code in the phone number.", [MessageType]::Warning);
                                }
                            }
                        }
                        try
                        {
                            $criticalAlertList = @()
                            $alertArm =  $this.LoadServerConfigFile("Subscription.AlertARM.json");
                            $alert = ($alertArm.resources | Select -First 1).PSObject.Copy()
                            $enabledAlerts | ForEach-Object {
                                $alertObj =  [Helpers]::DeepCopy($alert)
                                $alertObj.name = $_.Name
                                $alertObj.properties.description = $_.Description                                
                                $alertObj.properties.condition.allOf[2].anyOf =@()
                                $_.OperationNameList | ForEach-Object {
                                    $alertObj.properties.condition.allOf[2].anyOf += @{ field = "operationName"; equals =$_ }
                                }
                                if($isTargetResourceGroup)
                                {
                                    $alertObj.properties.condition.allOf += @{field= "resourceGroup";equals= $targetResourceGroup}    
                                }
                                
                                if($_.Name -eq "AzSK_Critical_Alert")
                                {
                                    if(-not [string]::IsNullOrWhiteSpace($criticalAlertActionGroupResourceId))
                                     {
                                      $alertObj.properties.actions.actionGroups[0].actionGroupId = $criticalAlertActionGroupResourceId
                                      $criticalAlertList += $alertObj
                                    }            
                                }
                                else
                                {
                                  $alertObj.properties.actions.actionGroups[0].actionGroupId = $actionGroupResourceId
                                  $criticalAlertList += $alertObj
                                }
                                
                                #$criticalAlertList += $alertObj
                            }
                            $alertArm.resources = $criticalAlertList 
                            $armTemplatePath = [Constants]::AzSKTempFolderPath + "Subscription.AlertARM.json";
                            $alertArm | ConvertTo-Json -Depth 100  | New-Item $armTemplatePath -Force | Out-Null
                            $alertDeployment = New-AzureRmResourceGroupDeployment -Name "AzSKAlertsDeployment" -ResourceGroupName $this.ResourceGroup -TemplateFile $armTemplatePath  -ErrorAction Stop                            
                            Remove-Item $armTemplatePath  -ErrorAction SilentlyContinue
                        }
                        catch
                        {
                            $messages += [MessageData]::new("Error while deploying alerts to the subscription", $_, [MessageType]::Error);                            
                        }            

                        [MessageData[]] $resultMessages = @();
                        #Logic to validate if Alerts are configured.
                        $configuredAlerts = @();        
                        $configuredAlerts = Get-AzureRmResource -ResourceType "Microsoft.Insights/activityLogAlerts" -ResourceGroupName  $this.ResourceGroup 
                        $actualConfiguredAlertsCount = ($configuredAlerts | Measure-Object).Count
                        $notConfiguredAlertsCount = $enabledAlerts.Count - $actualConfiguredAlertsCount
                        if( $actualConfiguredAlertsCount -ge  $enabledAlerts.Count)
                        {
                            #setting the tag at AzSKRG
                            $azskRGName = [ConfigurationManager]::GetAzSKConfigData().AzSKRGName;
                            [Helpers]::SetResourceGroupTags($azskRGName,@{[Constants]::AzSKAlertsVersionTagName=$this.AlertPolicyObj.Version}, $false)

                            #After successfully setting V2 alerts, clean V1 alert rules
                                            
                            $resultMessages += [MessageData]::new("All AzSK alerts have been configured successfully.`r`n", [MessageType]::Update);
                            #$this.UpdateActionGroupWebhookUri($existingWebhookUri);
                        
                        }                    
                        else
                        {
                            $resultMessages += [MessageData]::new("$notConfiguredAlertsCount/$($enabledAlerts.Count) alert group(s) have not been added to the subscription. Please add the alerts manually.", [MessageType]::Error);
                            $resultMessages += [MessageData]::new("$actualConfiguredAlertsCount/$($enabledAlerts.Count) alert group(s) have been added to the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update);
                        }
                    
                        $messages += $resultMessages;
                        $this.PublishCustomMessage($resultMessages);
                    }
                }
                else
                {
                    $this.PublishCustomMessage("No alerts have been found that matches the specified tags. Tags:[$([string]::Join(",", $this.FilterTags))].", [MessageType]::Warning);
                }
            }
            else
            {
                $this.PublishCustomMessage("No alerts found in the alert policy file", [MessageType]::Warning);
            }
        }
        $this.UpdateActionGroupWebhookUri($webhookUri);
        #$curActionGroup = $this.GetAlertActionGroupId([OldConstants]::AzSDKRGName);
        #if($curActionGroup)
        #{
        # Find-AzureRmResource -ResourceGroupNameEquals $([OldConstants]::AzSDKRGName) -ResourceType "Microsoft.Insights/activityLogAlerts" -ErrorAction SilentlyContinue | Remove-AzureRmResource -Force -ErrorAction SilentlyContinue
        # Find-AzureRmResource -ResourceGroupName $([OldConstants]::AzSDKRGName) -ResourceType "Microsoft.Insights/actiongroups" -ErrorAction SilentlyContinue | Remove-AzureRmResource -Force -ErrorAction SilentlyContinue
        #}
        return $messages;
    }

    [MessageData[]] SetAlerts()
    {
        [MessageData[]] $messages = @();
        #$curActionGroupResource = $this.GetAlertActionGroupId([OldConstants]::AzSDKRGName);
        #$newActionGroupResource = $this.GetAlertActionGroupId([ConfigurationManager]::GetAzSKConfigData().AzSKRGName);
        ##TODO check for azsk alert contact phone number feature
        #if($curActionGroupResource)
        #{
        # $curActionGroupResourceData= Get-AzureRmResource -ResourceId $curActionGroupResource.ResourceId
        # $securityPOCEmails = $curActionGroupResourceData.properties.emailReceivers
        # $smsReceivers = $curActionGroupResourceData.properties.smsReceivers
        # return $this.SetAlerts($securityPOCEmails,$smsReceivers);
        #}
        #elseif($newActionGroupResource)
        #{
            return $this.SetAlerts($null,$null,$null,$null,$null,$null,$null);
        #}
        #return $messages;
        
    }

    [MessageData[]] SetAlerts([string] $targetResourceGroup, [string] $securityContactEmails, [string] $SecurityPhoneNumbers, [string] $alertResourceGroupLocation)
    {
        return $this.SetAlerts($targetResourceGroup,$securityContactEmails,$SecurityPhoneNumbers,$alertResourceGroupLocation, $null, $null, $null);
    }

    [MessageData[]] SetAlerts([PSObject] $emailReceivers, [PSObject] $smsReceivers, [string] $webhookUri)
    {
        return $this.SetAlerts($null, $null ,$null, $null, $emailReceivers, $smsReceivers, $webhookUri);
    }

    hidden [string] SetupAlertActionGroup([string[]] $securityContactEmails,[string] $SecurityPhoneNumbers, [PSObject] $CurEmailReceivers)
    {
        $actionGroupResourceId = $null
        try{
            #Get ARM template for action group
            $actionGroupArm = $this.LoadServerConfigFile("Subscription.AlertActionGroup.json");
            $actionGroupArmResource = $actionGroupArm.resources | Where-Object { $_.Name -eq $([Constants]::AlertActionGroupName) } 
            $emailReceivers = $actionGroupArmResource.properties.emailReceivers | Select-Object -first 1
            if(($securityContactEmails | Measure-Object).Count -gt 0)
            {
                $emailReceiversList = @();
                $Counter = 1;
                $securityContactEmails | ForEach-Object {
                    $email = $emailReceivers.PsObject.Copy()
                    $email.name = "SecurityContactEmail$Counter"
                    $email.emailAddress = $_
                    $emailReceiversList += $email  
                    $Counter+=1
                }
                $actionGroupArmResource.properties.emailReceivers = $emailReceiversList
            }
            elseif(($CurEmailReceivers | Measure-Object).Count -gt 0)
            {
                $emailReceiversList = @();
                $CurEmailReceivers | ForEach-Object {
                    $email = $emailReceivers.PsObject.Copy()
                    $email.name = $_.name
                    $email.emailAddress = $_.emailAddress
                    $emailReceiversList += $email  
                }
                $actionGroupArmResource.properties.emailReceivers = $emailReceiversList;
            }

            $actionGroupArmResource.properties.PSObject.Properties.Remove('smsReceivers')        
            $armTemplatePath =[Constants]::AzSKTempFolderPath + "Subscription.AlertActionGroup.json"
            $actionGroupArm | ConvertTo-Json -Depth 100  | New-Item $armTemplatePath -Force
            $actionGroupResource = New-AzureRmResourceGroupDeployment -Name "AzSKAlertActionGroupDeployment" -ResourceGroupName $this.ResourceGroup -TemplateFile $armTemplatePath  -ErrorAction Stop
            $actionGroupId = $actionGroupResource.Outputs | Where-Object actionGroupId 
            $actionGroupResourceId = $actionGroupId.Values | Select -ExpandProperty Value                      
            Remove-Item $armTemplatePath  -ErrorAction SilentlyContinue
        }
        catch
        {            
            $this.PublishException($_);
        }
        
        return     $actionGroupResourceId
    }
    hidden [string] SetupAlertActionGroup([string] $SecurityPhoneNumbers, [PSObject] $CurSMSReceivers)
    {
        $actionGroupResourceId = $null
        try{
            #Get ARM template for action group
            $actionGroupArm = $this.LoadServerConfigFile("Subscription.AlertActionGroup.json");
            $actionGroupArmResource = $actionGroupArm.resources | Where-Object { $_.Name -eq $([Constants]::AlertActionGroupName) } 
            $actionGroupArmResourceOutput = $actionGroupArm.outputs.actionGroupId
            $actionGroupArmResource.name="AzSKCriticalAlertActionGroup"
            $actionGroupArmResourceOutput.value = $actionGroupArmResourceOutput.value.Replace($([Constants]::AlertActionGroupName),$([Constants]::CriticalAlertActionGroupName));
            $actionGroupArmResource.properties.PSObject.Properties.Remove('emailReceivers')
            if(-not [string]::IsNullOrWhiteSpace($SecurityPhoneNumbers))
            {
                $smsReceivers = $actionGroupArmResource.properties.smsReceivers | Select-Object -first 1
                $allPhoneNumbers = @();        
                $allPhoneNumbers += $this.ConvertToStringArray($SecurityPhoneNumbers);
                $Counter = 1;
                $smsReceiversList = @();
                    foreach($allPhoneNumber in $allPhoneNumbers ) {
                    $phoneNumberDetails = $smsReceivers.PsObject.Copy()
                    $phoneNumberDetails.name = "SecurityPhoneNumber$Counter"
                    $startIndex=$allPhoneNumber.indexof("-")  
                    if($startIndex -ne -1)
                    {
                     $countryCode=$allPhoneNumber.substring(0,$startIndex) -replace '[^0-9]', ''
                     $phoneNumberDetails.countrycode= $countryCode
                    }
                    else
                    {
                     return $actionGroupResourceId
                    }
                    $phoneNumber=$allPhoneNumber.substring($startIndex+1) -replace '[^0-9]', ''
                    $phoneNumberDetails.phoneNumber = $phoneNumber
                    $smsReceiversList += $phoneNumberDetails                
                    $Counter+=1        
                }
                $actionGroupArmResource.properties.smsReceivers = $smsReceiversList
            }
            elseif($null -ne $CurSMSReceivers)
            {
                $smsReceivers = $actionGroupArmResource.properties.smsReceivers | Select-Object -first 1
                $smsReceiversList = @();
                $CurSMSReceivers | ForEach-Object {
                    $smsReceiver = $smsReceivers.PsObject.Copy()
                    $smsReceiver.name = $_.name
                    $smsReceiver.countrycode = $_.countrycode
                    $smsReceiver.phoneNumber = $_.phoneNumber
                    $smsReceiversList += $smsReceiver  
                }
                $actionGroupArmResource.properties.smsReceivers = $smsReceiversList;
            }
            else
            {
              return $actionGroupResourceId
            }
            $armTemplatePath =[Constants]::AzSKTempFolderPath + "Subscription.AlertActionGroup.json"
            $actionGroupArm | ConvertTo-Json -Depth 100  | New-Item $armTemplatePath -Force
            $actionGroupResource = New-AzureRmResourceGroupDeployment -Name "AzSKAlertActionGroupDeployment" -ResourceGroupName $this.ResourceGroup -TemplateFile $armTemplatePath  -ErrorAction Stop
            $actionGroupId = $actionGroupResource.Outputs | Where-Object actionGroupId 
            $actionGroupResourceId = $actionGroupId.Values | Select -ExpandProperty Value                      
            Remove-Item $armTemplatePath  -ErrorAction SilentlyContinue
        }
        catch
        {    #Eating up this error
            #$this.PublishException($_);
        }
        
        return     $actionGroupResourceId
    }

    hidden [MessageData[]] CleanV1Alerts()
    {
        #Validate if V1(Old) Alert RG present
        $messages = @();
        $existingRG = Get-AzureRmResourceGroup -Name $this.V1AlertRGName -ErrorAction SilentlyContinue
        if($existingRG)
        {
            # Remove all locks
            $messages += $this.RemoveAllResourceGroupLocks();
            $messages += [MessageData]::new("Found old deprecated alert resource group (AzSKAlertsRG). Removing all V1 AzSK configured alerts by removing deprecated resource group");
            Remove-AzureRmResourceGroup -Name $this.V1AlertRGName -Force
        }

        return $messages
    }

    hidden [MessageData[]] RemoveAllResourceGroupLocks()
    {
        $messages = @();
        #Remove Resource Lock on Resource Group if any
        $locks = @();
        $locks += Get-AzureRmResourceLock -ResourceGroupName $this.V1AlertRGName
        if($locks.Count -ne 0)
        {
            $messages += [MessageData]::new("Removing following existing resource group locks so that old alert RG can be removed.", $locks);

            $locks | ForEach-Object {
                Remove-AzureRmResourceLock -LockId $_.LockId -Force | Out-Null
            }
            Start-Sleep -Seconds 60
        }
        return $messages;
    }

    hidden [string] GetV1AlertSecurityEmailContact()
    {
        #Validate if V1(Old) Alert RG present
        $existingRG = Get-AzureRmResourceGroup -Name $this.V1AlertRGName -ErrorAction SilentlyContinue
        $emailList  = [string]::Empty
        if($existingRG)
        {
            #Check if V1 alert resource is present
            $configuredAlerts = Get-AzureRmResource -ResourceGroup $this.V1AlertRGName -ResourceType 'microsoft.insights/alertrules' 
            if(($configuredAlerts | Measure-Object).Count -gt 0)
            {
                #Validate if command exists. As this command will soon get deprecated from AzureRM
                if (Get-Command "Get-AzureRmAlertRule" -errorAction SilentlyContinue)
                {
                    $alertResourceDetails = $configuredAlerts | Select -First 1
                    $alertRuleDetails = Get-AzureRMAlertRule -ResourceGroup $this.V1AlertRGName -Name $alertResourceDetails.Name -WarningAction SilentlyContinue
                    if($alertRuleDetails)
                    {
                        $emailList = [string]::Join(",",($alertRuleDetails.Actions | Select @{N='EmailList';E={$_.CustomEmails}} ).EmailList)
                            
                    }                        
                }                  
            }            
        }
        return $emailList     
    }

    hidden [PSObject] GetAlertActionGroup($rgName, $actionGroupName)
    {
        #Validate if Alert RG present
        $existingRG = Get-AzureRmResourceGroup -Name $rgName -ErrorAction SilentlyContinue
        if($existingRG)
        {
            $AGRSource = Find-AzureRmResource -ResourceType  microsoft.insights/actiongroups -ResourceGroupName $rgName -ResourceNameEquals $actionGroupName
            return $AGRSource;
        }
        else
        {
            return $null
        }    
    }
    hidden [string] ComputeAlertRunbookWebhookUri()
    {
        $actionGroupResource = $this.GetAlertActionGroup($this.ResourceGroup, [Constants]::AlertActionGroupName);
        $existingWebhookUri = $null;
        if($null -eq $actionGroupResource)
        {                      
            $existingWebhookUri=$null;
        }
        else
        { 
              $existingActionGrp= Get-AzureRmResource -ResourceId $actionGroupResource.ResourceId
              if(($existingActionGrp.Properties.webhookReceivers | Measure-Object).Count -gt 0)
              {
                $webhookReceivers=$existingActionGrp.Properties.webhookReceivers | Select-Object -first 1
                $existingWebhookUri=$webhookReceivers.serviceUri;
              }
              else
              {
                $existingWebhookUri=$null;
              }
        }
        return $existingWebhookUri
    }


    hidden [string] UpdateActionGroupWebhookUri([string] $existingWebhookUri)
    {
     #pass webhook uri if exist n actiongrp(update SS cmd) or create a new webhook uri(install CA ,update CA)
      $actionGroupResourceId = $this.GetAlertActionGroup($this.ResourceGroup, [Constants]::AlertActionGroupName)
      $runBookResourceID= $this.GetAlertRunBookResourceId()
      #check for empty string
      if($null -ne $actionGroupResourceId -and (-not [string]::IsNullOrWhiteSpace($runBookResourceID)))
      {
         $existingActionGrp= Get-AzureRmResource -ResourceId $actionGroupResourceId.ResourceId
         $webhookReceiversList = @();
         if(-not [string]::IsNullOrWhiteSpace($existingWebhookUri))
         {
          $webhookUri=$existingWebhookUri;
         }
         else
         {
          $webhookUri=$this.GetAlertRunBookWebHookUri();
         }    
         $props = @{
                    name = "WebHookForMonitoringAlerts"
                    serviceUri=$webhookUri
                   }
         $object = new-object psobject -Property $props
         $webhookReceiversList += $object 
         $existingActionGrp.Properties.webhookReceivers=$webhookReceiversList
         $existingActionGrp | Set-AzureRmResource -Force

      }
      return [string]::Empty
    }
    hidden [string] RemoveActionGroupWebhookUri()
    {
      $actionGroupResourceId = $this.GetAlertActionGroup($this.ResourceGroup, [Constants]::AlertActionGroupName)
      $runBookResourceID= $this.GetAlertRunBookResourceId()

      if($null -ne $actionGroupResourceId -and (-not [string]::IsNullOrWhiteSpace($runBookResourceID)))
      {
       try
       {
         $existingActionGrp= Get-AzureRmResource -ResourceId $actionGroupResourceId.ResourceId
         $webhookReceiversList = @();
         $existingActionGrp.Properties.webhookReceivers=$webhookReceiversList
         $existingActionGrp | Set-AzureRmResource -Force
         #Remove Webhook from Automation Runbook as well
         Remove-AzureRmAutomationWebhook -Name $this.AutomationWebhookName -ResourceGroup $this.ResourceGroup -AutomationAccountName $this.AutomationAccountName -ErrorAction SilentlyContinue
       }
       catch
       {
       }
      }
      return [string]::Empty
    }
    hidden [string] GetAlertRunbookResourceId()
    {
        #Validate if Alert RG present $this.ResourceGroup
        #$existingRG = Get-AzureRmResourceGroup -Name "azsdktashuk" -ErrorAction SilentlyContinue
        $existingRG = Get-AzureRmResourceGroup -Name $this.ResourceGroup -ErrorAction SilentlyContinue
        if($existingRG)
        {
            #$AlertRunBook = Find-AzureRmResource -ResourceType "Microsoft.Automation/automationAccounts/runbooks" -ResourceGroupName "azsdktashuk" -ResourceNameEquals "AutomationForAlerts/RunbookFrSQL"
             $resourceName=$this.AutomationAccountName+"/"+$this.RunbookName
             $AlertRunBook = Find-AzureRmResource -ResourceType  "Microsoft.Automation/automationAccounts/runbooks" -ResourceGroupName $this.ResourceGroup -ResourceNameEquals $resourceName
            if($AlertRunBook )
            {
                return $AlertRunBook.ResourceId
            }
            else
            {
                return [string]::Empty
            }            
        }
        else
        {
            return [string]::Empty
        }    
    }
    hidden [string] GetAlertRunBookWebHookUri()
    {    
        try
        {
        $webhookExpiryDate=(Get-Date).AddDays($this.WebhookExpiryInDays)
        Remove-AzureRmAutomationWebhook -Name $this.AutomationWebhookName -ResourceGroup $this.ResourceGroup -AutomationAccountName $this.AutomationAccountName -ErrorAction SilentlyContinue
        $Webhook = New-AzureRmAutomationWebhook -Name $this.AutomationWebhookName -IsEnabled $True -ExpiryTime $webhookExpiryDate -RunbookName $this.RunbookName -ResourceGroup $this.ResourceGroup -AutomationAccountName $this.AutomationAccountName -Force
        $NewWebHookUri=$Webhook.WebhookURI
        return $NewWebHookUri;        
        }
        catch{
          $this.PublishException($_)
          return [string]::Empty
        }
    }
}