Framework/Configurations/ContinuousAssurance/Continuous_Assurance_ScanOnTrigger_Runbook.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
Param(
    [object] $WebHookData
)

$AzSKRunbookVersion = "[#runbookVersion#]"

#Telemetry functions -- start here
function SetCommonProperties([psobject] $EventObj) {
    $notAvailable = "NA"
    $eventObj.data.baseData.properties.Add("JobId",$PsPrivateMetaData.JobId.Guid)
    $eventObj.data.baseData.properties.Add("SubscriptionId",$RunAsConnection.SubscriptionID)
    $eventObj.data.baseData.properties.Add("AzSKRunbookVersion", $AzSKRunbookVersion)
}

function GetEventBaseObject([string] $EventName) {
    $eventObj = "" | Select-Object data, iKey, name, tags, time
    $eventObj.iKey = $telemetryKey
    $eventObj.name = "Microsoft.ApplicationInsights." + $telemetryKey.Replace("-", "") + ".Event"
    $eventObj.time = [datetime]::UtcNow.ToString("o")

    $eventObj.tags = "" | Select-Object ai.internal.sdkVersion
    $eventObj.tags.'ai.internal.sdkVersion' = "dotnet: 2.1.0.26048"

    $eventObj.data = "" | Select-Object baseData, baseType
    $eventObj.data.baseType = "EventData"
    $eventObj.data.baseData = "" | Select-Object ver, name, measurements, properties

    $eventObj.data.baseData.ver = 2
    $eventObj.data.baseData.name = $EventName

    $eventObj.data.baseData.measurements = New-Object 'system.collections.generic.dictionary[string,double]'
    $eventObj.data.baseData.properties = New-Object 'system.collections.generic.dictionary[string,string]'

    return $eventObj;
}

function PublishEvent([string] $EventName, [hashtable] $Properties, [hashtable] $Metrics) {
    try {
        #return if telemetry key is empty
        if ([string]::IsNullOrWhiteSpace($telemetryKey)) { return; };

        $eventObj = GetEventBaseObject -EventName $EventName
        SetCommonProperties -EventObj $eventObj

        if ($null -ne $Properties) {
            $Properties.Keys | ForEach-Object {
                try {
                    if (!$eventObj.data.baseData.properties.ContainsKey($_)) {
                        $eventObj.data.baseData.properties.Add($_ , $Properties[$_].ToString())
                    }
                }
                catch
                {
                    # Left blank intentionally
                    # Error while sending CA events to telemetry. No need to break the execution.
                }
            }
        }
        if ($null -ne $Metrics) {
            $Metrics.Keys | ForEach-Object {
                try {
                    $metric = $Metrics[$_] -as [double]
                    if (!$eventObj.data.baseData.measurements.ContainsKey($_) -and $null -ne $metric) {
                        $eventObj.data.baseData.measurements.Add($_ , $Metrics[$_])
                    }
                }
                catch {
                    # Left blank intentionally
                    # Error while sending CA events to telemetry. No need to break the execution.
                }
            }
        }

        $eventJson = ConvertTo-Json $eventObj -Depth 100 -Compress

        Invoke-WebRequest -Uri "https://dc.services.visualstudio.com/v2/track" `
            -Method Post `
            -ContentType "application/x-json-stream" `
            -Body $eventJson `
            -UseBasicParsing | Out-Null
    }
    catch {
        # Left blank intentionally
        # Error while sending CA events to telemetry. No need to break the execution.
    }
}
#Telemetry functions -- end here


#function to invoke script from server
function InvokeScript($accessToken, $policyStoreURL,$fileName, $version)
{
    [System.Uri] $validatedURI = $null;
    $URI = $global:ExecutionContext.InvokeCommand.ExpandString($policyStoreURL)
    $result = "Write-Host 'Error connecting to AzSK policy store server.'"
    if([System.Uri]::TryCreate($URI, [System.UriKind]::Absolute, [ref] $validatedURI))
    {
        if($accessToken)
        {
            $retry = 3
            while($retry -gt 0)
            {
                $retry = $retry - 1
                $result = Invoke-WebRequest $validatedUri -Headers @{"Authorization" = "Bearer $accessToken"} -UseBasicParsing
                 if ($null -ne $result -and $result.StatusCode -ge 200 -and $result.StatusCode -le 399) {
                    $retry = -1;
                }
            }

        }
        else
        {
            $retry = 3
            while($retry -gt 0)
            {
                $retry = $retry - 1
                $result = Invoke-WebRequest $validatedUri -UseBasicParsing
                if ($null -ne $result -and $result.StatusCode -ge 200 -and $result.StatusCode -le 399) {
                    $retry = -1;
                }
            }
        }
        Invoke-Expression $result;
    }
}

function GetResourceDetailsfromWebhook($WebHookDataforResourceCreation)
{
    #Getting required properties of WebhookData.
            $WebhookName    =   $WebHookDataforResourceCreation.WebhookName
            $WebhookBody    =   $WebHookDataforResourceCreation.RequestBody
            $WebhookHeaders =   $WebHookDataforResourceCreation.RequestHeader

           # Obtain the WebhookBody containing the AlertContext
            $WebhookBody = (ConvertFrom-Json -InputObject $WebhookBody)
            Write-Output "`nWEBHOOK BODY"
            Write-Output "============="
            Write-Output $WebhookBody

             # Obtain the AlertContext
            $AlertContext = [object]$WebhookBody.data.context 
            $AlertContext 
            
            if($alertcontext -ne $null -and ![string]::IsNullOrWhiteSpace($alertcontext.activityLog) -and ![string]::IsNullOrWhiteSpace($alertcontext.activityLog.resourceGroupName))
            {
                $resourcedetails = @{ResourceGroupNamefromWebhook = $alertcontext.activityLog.resourceGroupName ; ResourceNamefromWebhook = ""}
            }
            else
            {
                $resourcedetails = @{ResourceGroupNamefromWebhook = "" ; ResourceNamefromWebhook = ""}
            }
             # Some selected AlertContext information
            #Write-Output "`nALERT CONTEXT DATA"
            #Write-Output "==================="
            #Write-Output $alertcontext.activityLog.eventSource
            #Write-Output $alertcontext.activityLog.subscriptionId
            #Write-Output $alertcontext.activityLog.resourceGroupName
            #Write-Output $alertcontext.activityLog.operationName
            #Write-Output $alertcontext.activityLog.resourceType
            #Write-Output $alertcontext.activityLog.resourceId
            #Write-Output $alertcontext.activityLog.eventTimestamp

            #$resourceidsplit = $alertcontext.activityLog.resourceId -split '/'
            
            

            #Write-Output $resourceidsplit[6]

            #$datafromdeployment = Get-AzResourceGroupDeployment -ResourceGroupName $alertcontext.activityLog.resourceGroupName -Name $resourceidsplit[6] | ConvertTo-Json -Depth 10
            
            #if(-not [string]::IsNullOrWhiteSpace($datafromdeployment))
            #{
            # $datafromdeploymentbody = (ConvertFrom-Json -InputObject $datafromdeployment)
            # $resourcename = $datafromdeploymentbody.Parameters.name.Value

            # Write-Output $resourcename

            # $resourcedetails = @{ResourceGroupNamefromWebhook = $alertcontext.activityLog.resourceGroupName ; ResourceNamefromWebhook = $resourcename}
            #}
            #else
            #{
            # $resourcedetails = @{ResourceGroupNamefromWebhook = "" ; ResourceNamefromWebhook = ""}
            #}

            return $resourcedetails;
}

######################################################################################################################
#Core runbook code.
#This is built using the runbook code template inside \Modules\AzSK\<version>\Framework\Configurations\Continuous_Assurance_ScanOnTrigger_Runbook
#The placeholder values for various important variables are determined 'on the fly' based on the defaults that ship in AzSK.JSON
#file in the \Modules\AzSK\<version>\Framework\Configurations folder and the local AzSKSettings.JSON file in the %localappdata%\Microsoft\AzSK
#folder for the user setting up CA.
#This Runbook gets triggered when resource is created in the subscription.

#In an org-specific installation, various values from AzSK.JSON can be overridden in org policy and
#are picked up from the org-specific AzSK.JSON obtained from the serverUrl location (in AzSKSettings.JSON).
#In generic (org-neutral) setups these values are obtained from AzSK.JSON on a public CDN endpoint.
######################################################################################################################
try
{
    #start job timer
    $jobTimer = [System.Diagnostics.Stopwatch]::StartNew();

    #----------------------------------Config start------------------------------------------------------------------
    $automationAccountRG =  "[#automationAccountRG#]"
    $automationAccountName="[#automationAccountName#]"
    $telemetryKey ="[#telemetryKey#]"
    
    #This is the location from where policy is fetched at runtime.
    #This can be an org-specific URL (when org policy is set up) or, if generic org-neutral mode is used, it will just match the CoreSetupSrcUrl (below)
    #We will refer to this as org-policy store or org-policy url in comments below (with the above understanding)
    $onlinePolicyStoreUrl = "[#onlinePolicyStoreUrl#]"


    #This setting determines if the policy store enforces authentication. Generally 'false' for org-policy or OSS (org-neutral) context.
    $enableAADAuthForOnlinePolicyStore = "[#enableAADAuthForOnlinePolicyStore#]"
    $AzureEnv = "[#AzureEnvironment#]"
    #This is the script that is run to peform the actual scanning. This is fetched from the org-policy store if org-policy
    #is in use. If not, it is fetched from the default AzSK CDN.
    #This script basically allows orgs to customize/tweak the scripts that are run to perform the daily CA scans.
    $runbookScanAgentScript = "RunbookScanAgent.ps1"

    $azureRmResourceURI = "[#ManagementUri#]"
    
    #This is the Run-As (SPN) account for the runbook. It is read from the CA Automation account.
    $RunAsConnection = Get-AutomationConnection -Name "AzureRunAsConnection"

    #------------------------------------Execute RunbookCoreSetup.ps1 to download required modules-------------------------
    
    #Login to Azure
    if(!$RunAsConnection)
    {
        throw "Cannot login to Azure from AzSK CA runbook. Connection info for AzureRunAsConnection not found."
    }
    try
    {
        Write-Output("RB: Started runbook execution...")
        
        $appId = $RunAsConnection.ApplicationId 
        Write-Output ("RB: Logging in to Azure for appId: [$appId]")
        $Azlogin = Get-Command -Name "Connect-AzAccount" -ErrorAction SilentlyContinue
        $loginCmdlets = Get-Command -Noun "AzureRmAccount" -ErrorAction SilentlyContinue
        if($Null -ne $Azlogin)
        {
            Connect-AzAccount `
                -Environment $AzureEnv `
                -ServicePrincipal `
                -Tenant $RunAsConnection.TenantId `
                -ApplicationId $RunAsConnection.ApplicationId `
                -CertificateThumbprint $RunAsConnection.CertificateThumbprint | Out-Null
            
           Set-AzContext -SubscriptionId $RunAsConnection.SubscriptionID  | Out-Null
        }
        else
        {
        if($Null -ne $loginCmdlets)
        {
            #AzureRm.profile version = 5.x.x
            if($Null -ne ($loginCmdlets | Where-Object{$_.Name -eq "Connect-AzureRmAccount"}))
            {
                Connect-AzureRmAccount `
                -Environment $AzureEnv `
                -ServicePrincipal `
                -TenantId $RunAsConnection.TenantId `
                -ApplicationId $RunAsConnection.ApplicationId `
                -CertificateThumbprint $RunAsConnection.CertificateThumbprint | Out-Null
            }
            #AzureRm.profile version = 4.x.x
            elseif ($Null -ne ($loginCmdlets | Where-Object{$_.Name -eq "Add-AzureRmAccount"})) 
            {
                Add-AzureRmAccount `
                -EnvironmentName $AzureEnv `
                -ServicePrincipal `
                -TenantId $RunAsConnection.TenantId `
                -ApplicationId $RunAsConnection.ApplicationId `
                -CertificateThumbprint $RunAsConnection.CertificateThumbprint | Out-Null
            }
            else
            {
                throw "RB: Failed to login to Azure. Check if AzureRm.profile module is present."
            }
            Set-AzureRmContext -SubscriptionId $RunAsConnection.SubscriptionID  | Out-Null
        }
        else
        {
            throw "RB: Failed to login to Azure. Check if AzureRm.profile module is present."
        }
    }
}
    catch
    {
        Write-Output ("RB: Failed to login to Azure with AzSK AppId: [$appId].")
        throw $_.Exception
    }


    #This is a 'pseudo-version' and corresponds to the folder on the online policy store
    #from where the current CA core setup and scan agent scripts will be fetched.
    $caScriptsFolder = "1.0.0"

    $WebHookDataforResourceCreation = $WebHookData
    $ResourceGroupNamefromWebhook = ""
    $ResourceNamefromWebhook = ""

    #Fetching the webhook parameter and get resourcegroup name and resource name
    if($null -ne $WebHookDataforResourceCreation)
    {
        try
        {
            $resourcedetails = GetResourceDetailsfromWebhook -WebHookDataforResourceCreation $WebHookDataforResourceCreation
        }
        catch
        {
            Write-Output ("Failed to get the resource details from webhook.")
            throw $_.Exception
        }

        try
        {
            if(![string]::IsNullOrWhiteSpace($resourcedetails.ResourceGroupNamefromWebhook))
            {
                $automationjoblist =  Get-AzAutomationJob -RunbookName Continuous_Assurance_ScanOnTrigger_Runbook -ResourceGroupName $automationAccountRG -Status Running -AutomationAccountName $automationAccountName
                $automationjoblist | ForEach-Object {
                
                    $jobdetails = Get-AzAutomationJob -AutomationAccountName $_.AutomationAccountName -ResourceGroupName $_.ResourceGroupName -Id $_.JobId
                
                    $jobdetails = $jobdetails.JobParameters      
                    $jobdetailsBody    =   $jobdetails.webhookData.RequestBody
                    $jobdetailsBody = (ConvertFrom-Json -InputObject $jobdetailsBody)
                    $jobdetailsContext = [object]$jobdetailsBody.data.context
                    $rgname = $jobdetailsContext.activityLog.resourceGroupName
                    if($rgname -eq $resourcedetails.ResourceGroupNamefromWebhook)
                    {
                        $resourcedetails.ResourceGroupNamefromWebhook = ""
                    }
                }
            }
        }
        catch
        {
            Write-Output ("Failed to get the Job List for Automation account.")
            throw $_.Exception
        }
        

        $ResourceGroupNamefromWebhook = $resourcedetails.ResourceGroupNamefromWebhook
        $ResourceNamefromWebhook = $resourcedetails.ResourceNamefromWebhook

    }

    #-----------------------------------Config end-------------------------------------------------------------------------
    
    #-----------------------------------Telemetry script-------------------------------------------------------------------
    PublishEvent -EventName "CA Job Started" -Properties @{
        "OnlinePolicyStoreUrl"=$OnlinePolicyStoreUrl; `
        "AzureADAppId"=$RunAsConnection.ApplicationId
    }

    #------------------------------------Execute RunbookScanAgent.ps1 to scan subscription and resources-------------------
    #We start with a check for 'Get-AzSKAccessToken' to ensure that AzSK module is ready (and loaded)
    if((Get-Command -Name "Get-AzSKAccessToken" -ErrorAction SilentlyContinue|Measure-Object).Count -gt 0)
    {
        #If policy store authN is set to true, get a token. (mostly for org policy/OSS, this will be 'false')
        if($enableAADAuthForOnlinePolicyStore -eq "true")
        {
            Write-Output("RB: Getting token for authN to online policy store.")
            $accessToken = Get-AzSKAccessToken -ResourceAppIdURI $azureRmResourceURI
        }

        $isAzAutomationAvailable = Get-Command -Name "Get-AzAutomationSchedule" -ErrorAction SilentlyContinue
        $isAzAccountsAvailable =  Get-Module Az.Accounts
        if ((-not [string]::IsNullOrWhiteSpace($isAzAccountsAvailable)) -and (-not [string]::IsNullOrWhiteSpace($isAzAutomationAvailable)))
        {    
            $Global:isAzAvailable = $true
        }

        PublishEvent -EventName "CA Job Invoke Scan Started"
        Write-Output ("RB: Invoking scan agent script. PolicyStoreURL: [" + $onlinePolicyStoreUrl.Substring(0,15) + "*****]")
        InvokeScript -accessToken $accessToken -policyStoreURL $onlinePolicyStoreUrl -fileName $runbookScanAgentScript -version $caScriptsFolder
        Write-Output ("RB: Scan agent script completed.")
        PublishEvent -EventName "CA Job Invoke Scan Completed"
    }
    else
    {
        Write-Output("RB: Not triggering a scan. AzSK module not yet ready in the automation account. Will retry in the next run.")
    }
    Write-Output("RB: Runbook execution completed...")
    PublishEvent -EventName "CA Job Completed" -Metrics @{
    "TimeTakenInMs" = $jobTimer.ElapsedMilliseconds; `
    "SuccessCount" = 1
    }
}
catch
{
    Write-Output ("RB: Exception occurred in CA runbook...`r`nError details: " + ($_ | Out-String))
    PublishEvent -EventName "CA Job Error" -Properties @{ "ErrorRecord" = ($_ | Out-String) } -Metrics @{"TimeTakenInMs" =$jobTimer.ElapsedMilliseconds; "SuccessCount" = 0}
    throw;
}
#----------------------------------Runbook end-------------------------------------------------------------------------