Framework/Core/SubscriptionSecurity/Alerts.ps1

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 = "East US";
    hidden [PSObject] $AlertPolicyObj = $null
    hidden [string] $V1AlertRGName;
    Alerts([string] $subscriptionId, [InvocationInfo] $invocationContext, [string] $tags): 
        Base($subscriptionId, $invocationContext)
    {
        $this.V1AlertRGName = [Constants]::V1AlertRGName
        $this.ResourceGroup = [ConfigurationManager]::GetAzSdkConfigData().AzSDKRGName
        $this.AlertPolicyObj =  $this.LoadServerConfigFile("Subscription.InsARMAlerts.json");
        $this.Policy = $this.AlertPolicyObj.AlertList
        $this.FilterTags = $this.ConvertToStringArray($tags);
    }



    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)
    {
        [MessageData[]] $messages = @();

        # Check for existence of resource group

        $existingRG = Get-AzureRmResourceGroup -Name $this.ResourceGroup -ErrorAction SilentlyContinue
        if($existingRG)
        {
            $startMessage = [MessageData]::new("Found AzSDK alerts resource group: $($this.ResourceGroup)");
            $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))
                }
            }

            # 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  $this.ResourceGroup -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 AzSDKRG
                            $azsdkRGName = [ConfigurationManager]::GetAzSdkConfigData().AzSDKRGName;
                            [Helpers]::SetResourceGroupTags($azsdkRGName,@{[Constants]::AzSDKAlertsVersionTagName=$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 $this.REsourceGroup -Name "AzSDKAlertActionGroup" -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);

                    }
                }
                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 AzSDK configured alerts found in the subscription. Resource group not found: $($this.ResourceGroup)", [MessageType]::Warning);
        }
        return $messages;
    }

    [MessageData[]] SetAlerts([string] $targetResourceGroup, [string] $securityContactEmails,[string] $SecurityPhoneNumbers, [string] $alertResourceGroupLocation)
    {
        $actionGroupResourceId = $null
        [MessageData[]] $messages = @();
        if($this.Force -or -not ($this.IsLatestVersionConfiguredOnSub($this.AlertPolicyObj.Version,[Constants]::AzSDKAlertsVersionTagName,"Alerts")))
        {
            # 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 = $this.GetAlertActionGroupId()

                #If V2 AG is not present then try to get Security email contacts from V1 alerts
                if([string]::IsNullOrWhiteSpace($actionGroupResourceId))
                {
                    $securityContactEmails = $this.GetV1AlertSecurityEmailContact()
                }
            
                if([string]::IsNullOrWhiteSpace($securityContactEmails) -and [string]::IsNullOrWhiteSpace($actionGroupResourceId))
                {
                    $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;
                }            
            }

            $allEmails = @();        
            $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 AzSDK alerts. Total alerts: $($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]::NewAzSDKResourceGroup($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(-not [string]::IsNullOrWhiteSpace($allEmails))
                        {
                            $actionGroupResourceId = $this.SetupAlertActionGroup($allEmails,$SecurityPhoneNumbers)
                            if([string]::IsNullOrWhiteSpace($actionGroupResourceId))
                            {
                                $this.PublishCustomMessage("Not able to create alert action group. Validate detailed log for more details.", [MessageType]::Error);
                                return $messages
                            }
                        }
                        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}    
                                }
                                
                                $alertObj.properties.actions.actionGroups[0].actionGroupId = $actionGroupResourceId
                                $criticalAlertList += $alertObj
                            }
                            $alertArm.resources = $criticalAlertList 
                            $armTemplatePath = [Constants]::AzSdkTempFolderPath + "Subscription.AlertARM.json";
                            $alertArm | ConvertTo-Json -Depth 100  | New-Item $armTemplatePath -Force | Out-Null
                            $alertDeployment = New-AzureRmResourceGroupDeployment -Name "AzSDKAlertsDeployment" -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 -eq  $enabledAlerts.Count)
                        {
                            #setting the tag at AzSDKRG
                            $azsdkRGName = [ConfigurationManager]::GetAzSdkConfigData().AzSDKRGName;
                            [Helpers]::SetResourceGroupTags($azsdkRGName,@{[Constants]::AzSDKAlertsVersionTagName=$this.AlertPolicyObj.Version}, $false)

                            #After successfully setting V2 alerts, clean V1 alert rules
                                            
                            $resultMessages += [MessageData]::new("All AzSDK alerts have been configured successfully.`r`n", [MessageType]::Update);
                        
                        }                    
                        else
                        {
                            $resultMessages += [MessageData]::new("$notConfiguredAlertsCount/$($enabledAlerts.Count) alert(s) have not been added to the subscription. Please add the alerts manually.", [MessageType]::Error);
                            $resultMessages += [MessageData]::new("$actualConfiguredAlertsCount/$($enabledAlerts.Count) alert(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);
            }
        }
        $messages +=$this.CleanV1Alerts();
        return $messages;
    }

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

    hidden [string] SetupAlertActionGroup([string[]] $securityContactEmails,[string] $SecurityPhoneNumbers)
    {
        $actionGroupResourceId = $null
        try{
            #Get ARM template for action group
            $actionGroupArm = $this.LoadServerConfigFile("Subscription.AlertActionGroup.json");
            $actionGroupArmResource = $actionGroupArm.resources | Where-Object { $_.Name -eq "AzSDKAlertActionGroup" } 
            $emailReceivers = $actionGroupArmResource.properties.emailReceivers | Select-Object -first 1

            $emailReceiversList = @();
            $Counter = 1;
            $securityContactEmails | ForEach-Object {
                $email = $emailReceivers.PsObject.Copy()
                $email.name = "SecurityContactEmail$Counter"
                $email.emailAddress = $_
                $emailReceiversList += $email  
                $Counter+=1
            }
            $actionGroupArmResource.properties.emailReceivers = $emailReceiversList

            if(-not [string]::IsNullOrWhiteSpace($SecurityPhoneNumbers))
            {
                $smsReceivers = $actionGroupArmResource.properties.smsReceivers | Select-Object -first 1
                $allPhoneNumbers = @();        
                $allPhoneNumbers += $this.ConvertToStringArray($SecurityPhoneNumbers);
                $Counter = 1;
                $smsReceiversList = @();
                $allPhoneNumbers | ForEach-Object {
                    $phoneNumberDetails = $smsReceivers.PsObject.Copy()
                    $phoneNumberDetails.name = "SecurityPhoneNumber$Counter"
                    $phoneNumberDetails.phoneNumber = $_
                    $smsReceiversList += $phoneNumberDetails
                    $Counter+=1        
            }
                $actionGroupArmResource.properties.smsReceivers = $smsReceiversList
            }
            else
            {
                $actionGroupArmResource.properties.PSObject.Properties.Remove('smsReceivers')
            }
            $armTemplatePath =[Constants]::AzSdkTempFolderPath + "Subscription.AlertActionGroup.json"
            $actionGroupArm | ConvertTo-Json -Depth 100  | New-Item $armTemplatePath -Force
            $actionGroupResource = New-AzureRmResourceGroupDeployment -Name "AzSDKAlertActionGroupDeployment" -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 [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 (AzSDKAlertsRG). Removing all V1 AzSDK 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.Properties.Actions | Select @{N='EmailList';E={$_.CustomEmails}} ).EmailList)
                            
                    }                        
                }                  
            }            
        }
        return $emailList     
    }

    hidden [string] GetAlertActionGroupId()
    {
        #Validate if Alert RG present
        $existingRG = Get-AzureRmResourceGroup -Name $this.ResourceGroup -ErrorAction SilentlyContinue
        if($existingRG)
        {
            $AGRsource = Find-AzureRmResource -ResourceType  microsoft.insights/actiongroups -ResourceGroupName $this.ResourceGroup | Select-Object -First 1
            if($AGRsource)
            {
                return $AGRsource.ResourceId
            }
            else
            {
                return [string]::Empty
            }            
        }
        else
        {
            return [string]::Empty
        }    
    }
}