Implement conditional access on Azure AD Apps : Using Workload Identities Premium

Azure AD app do not honor conditional access policies levaraging IP restrictions.

Suppose we have a conditional access policy which restricts access to any app from any IP except certain IP ranges via a named location (in this case using my ISP network).

Interactive user login – Blocked

You will notice the user interactive sign-in gets blocked when coming from an IP outside of what is allowed.

Login using a service principal for Azure AD app – Allowed

In this section, we will see if you have credentials for Azure AD app, you can access resources depending on what permissions the app has. In this example, we would read all the emails.

Setup

Lets setup an Azure AD app with mail.read permission and a credential.

Code to get emails from all the mailboxes

Prerequisites : Install and import ExchangeOnlinemanagement and Microsoft.Graph modules

Install-Module ExchangeOnlineManagement
Import-Module ExchangeOnlineManagement
Install-Module Microsoft.Graph
Import-Module Microsoft.Graph

Replace the clientId and tenantId with the clientId of the app and the tenant id for your tenant respectively. When the script is run, please supply the credential created for the app.

# Import the required module
Import-Module Microsoft.Graph
$err_string= ''
# Set the necessary variables
$clientId = "7477abb4-xxxx-xxxx-xxxx-xxxxxx"
$tenantId = "c2b84b0b-xxxx-xxxx-xxxx-xxxxxxx"
$ClientSecretCredential = Get-Credential -Credential $clientId
 
# Connect to Microsoft Graph
Connect-MgGraph -TenantId $tenantId -ClientSecretCredential $ClientSecretCredential -NoWelcome
 
# Get all users in the tenant
$users = Get-MgUser
 
# Loop through each user
foreach ($user in $users) {
    # Get the user's mailbox
    try {
        $mailbox = Get-MgUserMailFolderMessage -UserId $user.Id -MailFolderId 'Inbox' -ErrorAction Stop
        $test = $user.Mail
        write-host "####### Reading emails for mailbox " -nonewline
        write-host $test -foreground red -nonewline
        write-host " ##########" 
        write-host "Found " -nonewline
        write-host $mailbox.Length -foreground red -nonewline
        write-host " email(s) " 
        foreach ($message in $mailbox) {
            # Print the message subject and received date
            Write-Output (" ----------------------------------------------------")
            Write-Output ("Subject: " + $message.Subject)
            Write-Output ("Received: " + $message.ReceivedDateTime)
            $body = $message.Body.Content -replace '<[^>]+>',''
            $body = $body.trim()
            Write-Output ("Body: " + $body)
        }
    write-host "`n"
    }
    catch
    { 
        $err_string = $_ | Out-String
    }
    if ($err_string -inotmatch "The mailbox is either inactive, soft-deleted, or is hosted on-premise")
    {
        Write-Host $err_string
    }
}
# Disconnect from Microsoft Graph
Disconnect-MgGraph

Running the above code by supplying the secret for the below and we can see we are still able to access all the emails. The service principle sign-in logs clearly note the access is from outside the IP address (from a foreign country) but the conditional access policy didn’t apply.

Using Microsoft Entra Workload ID to implement the conditional access

To address this, Microsoft has a new feature named Microsoft Entra Workload ID. Bad thing here is It needs Its own premium license. Good thing is you can try it out to see if this even works!
Login to the Entra ID portal as a global admininstrator and search for Workload Identities and activate the trial of 200 licenses for 90 days.

Then login to Microsoft Admin portal, and assign the users with “Micsoroft Entra Workload ID” license.

Once the license is assigned, login as the GA and licensed user to the the Entra portal.
Go to Protection > Conditional Access > Create.
There we see “Workload Identities” under “What does this policy apply to”.
Now, we can select the app we want to apply the conditional access with IP restriction.

Running the same code above would now show error noting the access has been blocked by the conditional access policy

Service principal sign-in logs would show the failure as well

Conclusion

Microsoft Entra Workload ID premium looks promising and goes much beyond the conditional access. Its worth looking at its capabilities.

https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-workload-id

Azure Policy – Deny creation of virtual machines without IP restriction across all Azure subscriptions

TLDR;

Public Azure virtual machines without any IP restriction is always an attack vector which may result in compromise of the VM and further lateral movement in Azure infrastructure.
Azure policy may be used to deny any attempt to even create the virtual machines without IP restriction.
This blog post has step-by-step process on how to implement an Azure policy on ALL your subscriptions covering IP restriction for ALL your future virtual machines.

What is Azure policy:

Azure policy is a service inside Azure that allows configuration management.It executes every time a new resource is added or an existing resource is changed. It has a set of rules, and set of actions. The Azure policy could report the event as non-compliant or even deny the action altogether if the rules are not matched.

Azure policy is an excellent way to enforce and bake-in security and compliance in the Azure infrastructure.
As you see in the below picture, Azure policy is an integral part of Azure Governance – mainly consisting of Policy Definitions and Policy Engine which works directly with Azure Resource Manager (ARM).

image 
Image source : https://www.microsoft.com/en-us/us-partner-blog/2019/07/24/azure-governance/

Summary:

If the Azure virtual machines need to be accessible over internet, Its important to restrict access its access ONLY from your corporate public IP addresses.
This will help in couple of situations :
a) Limit external access from an attacker.
b) Limit Insider threat or misuse from an employee.
The IP address restriction could be created while creating the virtual machine using network security groups.
However, enforcing this on the policy level by the administrator would ensure we are not dependent on individual team’s best judgment.

Process:

As a best practice, always test the policy in audit mode before switching to deny mode. In this walkthrough, we will follow below steps :

1) Create the policy definition.
2) Apply the policy (Policy Assignment) in audit mode
3) Test with Audit mode
3) Apply the policy (Policy Assignment) in deny mode
4) Test with Deny mode

Create the policy definition

On the search bar, search for “policy” and click on it.

image

Click Definitions and then click Policy Definitionimage

Click the … button under “Definition Location” to select the management group. If you want to apply this policy to all subscriptions, don’t select any subscription.
To apply this policy to a specific subscription, select the desired subscription under the subscription dropdown.

image

Policy Details:

Name:
Deny creation of virtual machine without access restricted only from company’s public IP addresses
(on-prem/VPN)

Description (Change the IP address list below):
Deny creation of virtual machine which does not have external company IP addresses restriction in the network security group.
One or more of the below corporate IP addresses must be specified in the network security group when creating the virtual machine. Otherwise, the validation will fail and the virtual machine will not be created.
Below is the valid public corporate IP addresses list :
208.114.51.253
104.104.51.253
108.104.51.253

Category : Network
image 
Policy Rule:

{
  "mode": "All",
  "policyRule": {
    "if": {
      "allOf": [
        {
          "field": "type",
          "equals": "Microsoft.Network/networkSecurityGroups"
        },
        {
          "count": {
            "field": "Microsoft.Network/networkSecurityGroups/securityRules[*]",
            "where": {
              "allOf": [
                {
                  "anyof": [
                    {
                      "field": "Microsoft.Network/networkSecurityGroups/securityRules[*].sourceAddressPrefix",
                      "notIn": [
                        "208.114.51.253",
                        "104.104.51.253",
                        "108.104.51.253"
                      ]
                    }
                  ]
                }
              ]
            }
          },
          "greater": 0
        }
      ]
    },
    "then": {
      "effect": "[parameters('effect')]"
    }
  },
  "parameters": {
    "effect": {
      "type": "String",
      "metadata": {
        "displayName": "Effect",
        "description": "The effect determines what happens when the policy rule is evaluated to match"
      },
      "allowedValues": [
        "audit",
        "deny"
      ],
      "defaultValue": "audit"
    }
  }
}

Policy Assignment

Under policy > definition, go to the newly created policy definition.
image

Click Assign.

image

Provide an assignment name and description
Name:
Deny creation of virtual machine without access restricted only from company’s public IP addresses
(on-prem/VPN)

Description (Change the IP address list below):
Deny creation of virtual machine which does not have external company IP addresses restriction in the network
security group.
One or more of the below corporate IP addresses must be specified in the network security group when creating the virtual machine. Otherwise, the validation will fail and the virtual machine will not be created.
Below is the valid public corporate IP addresses list :
208.114.51.253
104.104.51.253
108.104.51.253

image

Under “Parameters” tab, select “audit” in the Effect dropdown and click “Review+Create”

image

On the review page, click “Create” .

image

The policy assignment is created. Please note It takes about 30 minutes to take effect.

image

 

Test 1 – Audit mode :
Create virtual machine with RDP allowed from any external IP Address

With the policy in Audit mode, let us create a new virtual machine with RDP open to any external IP address.

image

image

image
When the policy is in the audit mode, the virtual machine creation is successful but Azure policy adds a Microsoft.Authorization/policies/audit/action operation to the activity log and marks the resource as non-compliant.

Activity Logsimage

Compliance State:
Policy > Compliance
image

Test 2 – Deny mode
Create virtual machine with RDP allowed from any external IP Address

We need to change the effect mode to “deny” in our policy assignment.
Head over to Policy > Assignments > Click on the policy we created

image
Click “Parameters” tab. Select “deny” from the dropdown and continue to save the policy assignment.

image

Attempt to create a virtual machine with the same settings as we did before.
image

When you proceed to create the virtual machine, the final validation will fail with an error message (left side) which when clicked will show which policy disallowed this action.

image

Clicking on the policy would show the policy assignment with details showing why the policy disallowed this action.

image

When the policy is in the deny mode, the virtual machine creation is successful but Azure policy adds a Microsoft.Authorization/policies/deny/action operation to the activity log and marks the resource as non-compliant.

Under activity logs, you can see the deny action.:
image

image

Summary :

Azure policy is an excellent way of enforcing compliance in Azure infrastructure. In this blog post we saw how we can apply Azure policy to deny creation of virtual machines without any IP restriction.
For further readings :
Azure policy docs : https://docs.microsoft.com/en-us/azure/governance/policy/overview
Azure policy Github : https://github.com/Azure/azure-policy