Recursively Searching Azure Subscription for SPN Role Assignments

The Azure RBAC is powerful that allows assignment of users or SPNs to a role on a different resource levels, like user John can be assigned as Contributor on a Subscription, Resource Group, or a Resource (e.g. Storage Account) level.

The same is true for SPN, that is, it can be assigned to resources at different hierarchical levels.

Azure RBAC Security Challenge

Because the role assignments can be done at any level of depth, there exist no one command in Azure PowerShell cmdlet (or API) to find that out. For auditing reasons, an Azure security engineer or Administrator may want to audit the assignments at different levels and maintain the inventory thereof.

Solution: Recursively search role assignments

The solution is to utilize the same available Azure PowerShell cmdlets in a smart manner to build out list of assignments of SPNs on different resource levels.

In the following example, you can specify the subscription name in place of <SUBSCRIPTION NAME> and specify the list of all SPNs that you want to search in the variable $spn below

Select-AzSubscription -SubscriptionName "<SUBSCRIPTION NAME>"
$spn=@("<SPN1>","<SPN2...>")

$Resources = Get-AzResource 
foreach ($Resource in $Resources) 
{
    $ass = Get-AzRoleAssignment -Scope $Resource.Id #| Where-Object {$_.DisplayName -in $spn}
    foreach ($ax in $ass) 
    {
        Write-Host $Resource.ResourceGroupName "`t" $ax.DisplayName "`t" $ax.ObjectType "`t" $ax.Scope "`t" $ax.RoleDefinitionName
    }
     
}

Note: Because this command recursively searches all the resources within a subscription, it may take several minutes to complete.

And since the above code simply writes to the console and not capturing in a list or table, you may also want to capture the output to a file. You can do so by using the Start-Transcript cmdlet to capture all the text written to console in form a file.

Leave a Reply