Microsoft Secure Tech Accelerator
Apr 03 2024, 07:00 AM - 11:00 AM (PDT)
Microsoft Tech Community
Automatically disable On-prem AD User using a Playbook triggered in Azure
Published Feb 09 2021 08:33 AM 23.1K Views
Microsoft

Many organizations have an on-premises Active Directory infrastructure that is synced to Azure AD in the cloud. However, given that the on-prem side is the authoritative source of truth, any changes, such as disabling a user in the cloud (Azure AD), are overridden by the setting defined in the on-prem AD during the next sync. This presents challenges when you want to orchestrate a user property change from Azure that needs to persist even after the sync happens.  To address the problem, this solution leverages the Automation Accounts and Hybrid Worker features across on-prem Windows resources & Azure . Automation Accounts can be used to perform cloud-based automation across Azure and non-Azure environments, including on Linux and Windows servers sitting in AWS, and GCP clouds so long as those machines have the Log Analytics agent installed.

 

Solution Overview

 

A typical use-case for this solution would flow as below:

 

i. Existing Microsoft Sentinel Analytics rule generates an incident requiring a user to be blocked from further domain access.

 

ii. The incident has the playbook attached to kick off the actions needed to block user access both on the cloud and on on-prem AD

 

iii. The playbook includes the "create hybrid automation job" action, which executes a PowerShell script against the on-prem DC to block the user.

 

iv. User blocked in iii. above remains blocked even after subsequent Azure AD connect syncs with Azure cloud.

 

Deployment Steps

 

High-level summary

 

Before you begin to review the pre-requisites of deploying a Hybrid Runbook Worker here: Deploy a Windows Hybrid Runbook Worker in Azure Automation | Microsoft Docs

 

i. Create Automation Account

ii. Deploy the Automation Hybrid Worker solution from the Azure Market place

iii. Create a Hybrid Worker Group

iv. Create a new PowerShell Runbook.

v. Register the Hybrid Worker with Azure

vi. Test the Runbook.

vii. Deploy/build the Playbook.

viii. Attach the Playbook to the relevant Analytics rule in Azure Sentinel.

 

Detailed steps

 

1. Create an Automation Account from the Azure Portal

02-Automationacc.png

2. Deploy the Automation Hybrid Worker solution from the Azure Market place

03-marketplace.png

 

From the same Automation Account menu, create a Hybrid Worker Group.

 

06-HybridWorkerGroup.png

 

05-credentials.png

 

It is highly recommended that the account's permissions be restricted to the minimum required to disable user accounts using the Delegation userAccountControl bitmask. More details can be found here: UserAccountControl property flags - Windows Server | Microsoft Docs

To create a new PowerShell Runbook, navigate to your Automation Account and select the Runbooks blade.
 
05-createrunbook.png

 

Select PowerShell from the Runbook type menu and paste the below script in the resulting window. Click save, then publish to activate the Runbook.
 
Note: the script also includes code to report an error in case of a failure in the process of disabling the account:

 

 

 

 

 

 

Param (

[string] $SAMAccountName

)

if (Get-Module -ListAvailable -Name ActiveDirectory) {
    Write-Output "ActiveDirectory PowerShell module already exists on host."
} 
else {
    Write-Output "ActiveDirectory PowerShell module does not exist on host. Installing..."
    try {
        Import-Module ActiveDirectory
    }
    catch{
        Write-Error "Error installing ActiveDirectory PowerShell module."
        throw $_
        break
    }

    Write-Output "ActiveDirectory PowerShell module installed."
}

Write-Output "Finding and disabling user $SAMAccountName"
try {
    Get-ADUser -Identity $SAMAccountName | Disable-ADAccount
}
catch {
    Write-Error "Error disabling user account $SAMAccountName"
    throw $_
    break
}
Write-Output "Successfully disabled user account $SAMAccountName"

 

 

 

 

 

 

The script takes in a SAMAccountName parameter which it uses to find the appropriate user and disable the account. This script can be modified to do various other tasks, such as password resets, adding/removing users to/from groups, etc.


Create a test user in Active Directory, then perform the steps in the on-prem machine to install the Hybrid Worker feature.

Deploy the below script from this URL: PowerShell Gallery | New-OnPremiseHybridWorker 1.7. Depending on the PowerShell module currently installed on your machine, you may need to download the file manually. If you do so, you will need to rename the extension to a .zip file first, then extract it to the directory you’ll execute the script from.

This script performs the following actions:
1) Install the necessary modules
2) Login to an Azure account
3) Check for the resource group and automation account
4) Create references to automation account attributes
5) Create a Log Analytics Workspace if needed
6) Enable the Azure Automation solution in Log Analytics
7) Download and install the Microsoft Monitoring Agent
8) Register the machine as a hybrid worker

To register your HybridWorker in Azure, add your hybrid runbook's details into the parameters to be passed to the creation command. Execute the below statement at your PowerShell prompt:
$NewOnPremiseHybridWorkerParameters = @{
AutomationAccountName = "iwauto"
AAResourceGroupName = "AD-Onprem"
OMSResourceGroupName = "AD-Onprem"
HybridGroupName = "AutoGroup"
SubscriptionID = "xxxxxxxxxxxxxxxx"
WorkspaceName = "iwautola"}
 
From the same PowerShell command prompt type: Install-Script -Name New-OnPremiseHybridWorker which will use parameters specified above.
This command will open a log-on screen to Azure Portal to register the Hybrid Worker in Azure.
 
The command will use the parameters specified above to register your Hybrid Worker Group in your Azure Subscription. You can learn more about the process of deploying Hybrid Workers here: Deploy a Windows Hybrid Runbook Worker in Azure Automation | Microsoft Docs

The command will open a logon screen in Azure Portal to register the Hybrid Worker in Azure.

 

07-azurereg.png

To confirm successful registration, navigate to your automation account, then select Hybrid worker groups. You should see the recently registered Hybrid Worker Group in the list in the below screenshot.

 

08-HybridWorker.png

 

If you get the error indicating that the PowerShell file is not digitally signed, then you will need to execute the command below:
Set-ExecutionPolicy RemoteSigned
 
You may still have to unblock the file in case changing the execution policy alone does not work. The command to do this is from a PowerShell prompt is:
Unblock-File -Path .\New-OmPremiseHybridWorker.ps1

It is also recommended that you use TLS versions more recent than 1.0 and 1.1. For this reason, you may be required to run the below command as well:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
 
You can learn more about the process of deploying Hybrid Workers here:
 
On successful registration, you should see an output similar to the below:
08-successoutput.png
To confirm successful registration, navigate to your automation account, then select Hybrid worker groups. You should see the recently registered hybrid worker group in the list in the below screenshot.
 
08-HybridWorker.png
 
 
Test the Runbook
To ensure the Runbook is working ok before integrating with a Logic App, execute the Runbook manually from the Azure Portal and specify a test account in the SAMAccountName box, select HybridWorker in the Run Settings section and then choose your Hybrid Worker group name from the drop-down list:
 
09-manualtest.png
 

 

Steps to orchestrate from Azure Sentinel/Logic Apps

Below is the structure of the orchestration Logic App that triggers the runbook to disable qualifying accounts from the On-Prem AD. With this action, the next on-prem to cloud AD sync will maintain the state on the account – in this case disabled, until the setting is reversed from the on-prem AD Users & Computers management console.

The high-Level structure of the Playbook

10-LogicAppOverview.png

 

The detailed structure of the Playbook:

Extract entity details (to capture user ID) following trigger execution

Createjob.png

Parse the JSON output from the Entities-Get Actions step above to extract the Azure User ID and SAM Account name needed to perform disable operations-first on Azure then on the On-Prem Active directory.

 

ParseJSON.png

 

Disable Account in Azure AD

DisableonAzureAD.png

 

Create Hybrid Automation Job
Createjob.png
 
The string function below is contained in the 'Runbook Parameter SamAccountName' above and is needed to extract the SAMAccount from the UPN of the user as the On-Prem AD can only act on the User ID when specified in this format:

substring(body('Parse_JSON')?['Name'], 0, sub(length(body('Parse_JSON')?['Name']),indexOf(body('Parse_JSON')?['Name'],'@')))

To simulate the block orchestration from Microsoft Sentinel, you may use the below sample query to create an Analytics rule that will detect a failed logon due to a wrong password entered on the Azure AD portal. You can then simulate failed logon attempts with the account you wish to test with.

SigninLogs
| where Location == "KE" and Identity contains "mytestaccount" and ResultType =="50126"
| extend AccountCustomEntity = AlternateSignInName

Troubleshooting guide for Hybrid Runbook Workers can be found here: Troubleshoot Azure Automation Hybrid Runbook Worker issues | Microsoft Docs
 

 

This Playbook can be deployed directly from GitHub on this link: Azure-Sentinel/Playbooks/Block-OnPremADUser at master · Azure/Azure-Sentinel (github.com)

 

Troubleshooting guide: Troubleshoot Azure Automation Hybrid Runbook Worker issues | Microsoft Docs

Special thanks to @haelshab for his valuable collaboration in this project & @Yaniv Shasha for suggestions to enhance the solution

 

 

10 Comments
Microsoft

Hello, 

 

Just to add that in case of ActiveDirectory module not present on the hybrid worker, the script cannot do the install by simple Import-Module, as this is only used for importing something already installedm and script will fail on the hybrid worker.

To have the ActiveDirectory module installed, you need to follow the documentations, ActiveDirectory Module | Microsoft Docs

 

"If you don't have the Active Directory module installed on your machine, you need to download the correct Remote Server Administration Tools (RSAT) package for your OS: Remote Server Administration Tools - Windows Server | Microsoft Docs"

 

Thank you,

 

Copper Contributor

Hello

 

Do you have the following information

 

" Parse the JSON output from the Entities-Get Actions step above to extract the Azure User ID and SAM Account name needed to perform disable operations-first on Azure then on the On-Prem Active directory."   The picture is little blurry and I cant see the information. 

Copper Contributor

@Dhaval ShastriIn our case we used this:

 

{
    "properties": {
        "$id": {
            "type""string"
        },
        "AadUserId": {
            "type""string"
        },
        "DisplayName": {
            "type""string"
        },
        "Name": {
            "type""string"
        },
        "Type": {
            "type""string"
        }
    },
    "type""object"
}
 
I recommend you to deploy it using the code provided in GitHub since there are some steps missing in this article. Then you can modify the Playbook at your convenience. That is how I did it and it works great!
Copper Contributor

Hello 

i have an error with substring(body('Parse_JSON')?['Name'], 0, sub(length(body('Parse_JSON')?['Name']),indexOf(body('Parse_JSON')?['Name'],'@')))

 

"InvalidTemplate. The length of substring can't be longer than '13' which is the length of the source string.https://aka.ms/logicexpressions#substring"

 

do you have any idea ? 

Is it better to disable UPN from local AD instead of trying to convert UPN from Azure AD to SAMaccount ?

Copper Contributor

@Wedge34In our case we had to modify it and in the “Create job” step “Runbook Parameter samAccountName”, use the below function:

 

concat(body('Parse_JSON')?['Name'],'@',body('Parse_JSON')?['UPNSuffix'])

 

Then in the disable account PowerShell script part for the Runbook, use the following:

 

Get-ADUser -Filter {UserPrincipalName -eq $SAMAccountName} |  Disable-ADAccount

 

It works like a charm!

Copper Contributor

Hello @AndyITech 

i have done exactly the same, thank you for you reply

Copper Contributor

Hello I tried this but the Runbooks fails with the error: "Disable-ADAccount : Insufficient access rights to perform the operation" but the service account for the hybrid worker has the needed permissions. Any idea why it fails?

Copper Contributor

I know this is an old thread, but I get the same error when trying to perform an "set" or "disable" action against AD on-prem using a Hybrid Worker.   The account I'm using is the default LocalSystem as I cannot supply a domain account that will work for some reason.  Has anyone got past this issue if were getting the insufficient access rights issue?

Microsoft

Hi @Vigitalmoe13 have you tried the below:

i. Azure AD Sync Connect issue with permission error 8344 - Microsoft Q&A

 

ii. Ensure that the user you are running AAD sync under, has the following permissions on the ‘root’ of your local AD domain.

  • Replicating Directory Changes: Allow
  • Replicating Directory Changes All: Allow     

 

iii. If you have Microsoft Defender for Identity you can follow the steps here as opposed to this logic app: Remediation actions - Microsoft Defender for Identity | Microsoft Learn

Copper Contributor

Hi All,

 

Is this guide outdated now I had to change the Trigger to the Sentinel Alert trigger to get this to work.

 

I am now seeing a new error

 

{
  "error": {
    "code""Authorization_RequestDenied",
    "message""Insufficient privileges to complete the operation.",
    "innerError": {
      "date""2023-03-30T18:35:45",
      "request-id""05dcf759-5d00-437d-b822-dbc8b134b572",
      "client-request-id""05dcf759-5d00-437d-b822-dbc8b134b572"
    }
  }
}

 

Can anyone assist?

Co-Authors
Version history
Last update:
‎Nov 01 2021 04:20 PM
Updated by: