Azure Run Command and VM extensions let anyone with the right Azure role run code as SYSTEM or an elevated user on a virtual machine without a network login, so detecting their misuse means watching the Azure control plane, not just the host. This how-to shows which events to collect, which detections to build, how to tell legitimate automation from an attacker, and what to do in the first hour after an alert.
The technique sits under MITRE ATT&CK T1651 Cloud Administration Command. Our T1651 Cloud Administration Command Defensive Guide explains the technique across cloud providers. This page is Azure-specific and limited to detection and response. Ransomware operators and other groups have used these features after taking over cloud identities; see our Storm-0501 Threat Actor Profile Guide for one actor's hybrid cloud tradecraft.
This is an independent guide from NHI Mgmt Group, based on Microsoft's public documentation as of November 2026. It is not sponsored or reviewed by Microsoft. Product features change, so confirm settings against Microsoft's current documentation.
Key takeaways
- Run Command and extensions are management features, not vulnerabilities. Abuse begins with a compromised identity that holds VM write rights, often a service principal or managed identity rather than a person.
- Windows Run Command scripts run as System; Linux scripts run as an elevated user. Both bypass network controls on the VM because the platform agent delivers the script.
- The Azure Activity Log is the primary detection source. Host logs and endpoint telemetry confirm what actually ran.
- Baseline who normally uses these operations. Most environments have a short list of automation identities and admins; anything else is worth a look.
- Microsoft Defender for Cloud publishes specific alerts for suspicious Run Command, Custom Script Extension, VMAccess and DSC use. Use them, and add your own rules for identity context they lack.
- Response starts with the identity: revoke the caller's access, then examine the VMs it touched.
Step 1: understand what you are detecting
Azure offers two flavours of Run Command. The Run Command overview describes action Run Command as a POST action with a 90-minute limit, running as the system account or root, one command at a time, and output limited to 4 KB. Managed Run Command is a resource type that can be deployed in templates, runs as a customer-specified user, supports multiple parallel or sequenced commands and scale set models, and can upload large output to a customer append blob. Up to 25 managed Run Commands can exist on a VM.
On Windows, running a command needs Microsoft.Compute/virtualMachines/runCommand/action, which Virtual Machine Contributor and higher roles hold, and scripts run as System. The built-in command IDs include RunPowerShellScript (the only one that accepts your own script) plus others that change security settings, such as DisableNLA, EnableAdminAccount, EnableRemotePS and DisableWindowsUpdate. Each of those is a useful attacker step in its own right.
On Linux, scripts run as an elevated user by default, and the documentation lists Microsoft.Compute/virtualMachines/runCommands/write as the permission to run a command, again held by Virtual Machine Contributor and higher. Example usage is az vm run-command invoke with RunShellScript.
VM extensions are small applications for post-deployment configuration, installed and removed through the platform without connecting to the VM. The ones most relevant to abuse are the Custom Script Extension (runs a supplied script or command), VMAccess (resets access and manages administrator accounts), Desired State Configuration (applies configuration that can include scripts), and monitoring or disk encryption extensions that can be repurposed for data collection or ransomware-style encryption.
Two points matter for detection. First, all of these are driven through Azure Resource Manager, so every use leaves a control plane record. Second, the caller's identity is the key attribute: a Run Command from your patching service principal at 02:00 is normal, the same call from a guest user's token is not.
Step 2: collect the right telemetry
You need three layers.
| Layer | Source | What it tells you |
|---|---|---|
| Control plane | Azure Activity Log, exported to Log Analytics or your SIEM | Who called which operation, on which VM, from which IP, and whether it succeeded |
| Identity | Microsoft Entra sign-in logs, including service principal and managed identity sign-ins | How the caller authenticated, from where, and whether the sign-in was risky or new |
| Host | Extension handler logs, process telemetry from endpoint detection and response, PowerShell script block logging | What the script actually did once it ran |
For the control plane, make sure every subscription exports its Activity Log through a diagnostic setting to a central workspace, and alert if that setting is removed. Our Azure Monitor, Activity Log and Diagnostic Settings Guide covers the setup. Activity Log retention in the platform is limited, so central export is what makes investigation possible weeks later.
On hosts, Microsoft documents handler logs for troubleshooting: on Windows under C:\WindowsAzure\Logs\Plugins\Microsoft.CPlat.Core.RunCommandWindows\<version>\RunCommandExtension.log, and on Linux at /var/log/azure/run-command/handler.log. Collect these with your log agent, and make sure your endpoint tool records process creation by the Azure guest agent and extension handlers, because attacker scripts appear as children of those processes.
Step 3: build control plane detections
The queries below are illustrative Kusto for the AzureActivity table. Operation names appear in OperationNameValue; check the exact casing and values in your own workspace before deploying, because they can differ by API version and export path.
Run Command by an unusual caller
let lookback = 30d;
let known = AzureActivity
| where TimeGenerated between (ago(lookback) .. ago(1d))
| where OperationNameValue has_any ("runCommand/action", "runCommands/write")
| distinct Caller;
AzureActivity
| where TimeGenerated > ago(1d)
| where OperationNameValue has_any ("runCommand/action", "runCommands/write")
| where Caller !in (known)
| project TimeGenerated, Caller, CallerIpAddress, ResourceGroup, _ResourceId, ActivityStatusValue
This flags any identity using Run Command for the first time in 30 days. Tune the lookback, and maintain an allowlist of known automation identities with the VMs or resource groups they are expected to touch.
Run Command across many VMs
AzureActivity
| where TimeGenerated > ago(1h)
| where OperationNameValue has_any ("runCommand/action", "runCommands/write")
| summarize VMs = dcount(_ResourceId), Subs = dcount(SubscriptionId) by Caller, bin(TimeGenerated, 15m)
| where VMs >= 5
Ransomware and mass credential theft often fan out across many machines quickly. Legitimate fleet operations usually run through a configuration management tool with a known identity, so a sudden fan-out from a different caller deserves an alert.
Extension installs and deletions
AzureActivity
| where TimeGenerated > ago(1d)
| where OperationNameValue has "virtualMachines/extensions"
| where OperationNameValue has_any ("write", "delete")
| extend Extension = tostring(split(_ResourceId, "/extensions/")[1])
| project TimeGenerated, Caller, CallerIpAddress, OperationNameValue, Extension, _ResourceId, ActivityStatusValue
Review installs of Custom Script Extension, VMAccess and DSC by callers outside your baseline, and treat a delete shortly after a write as a possible clean-up step. Scale set models have their own extension operations under virtualMachineScaleSets; include them.
Identity context joins
Enrich each hit with the caller's recent sign-ins. Useful flags are a sign-in from a new country or hosting provider IP, a service principal authenticating with a client secret when it normally uses a certificate or federation, a recent new credential added to the application, and a recent role assignment granting Virtual Machine Contributor, Contributor or Owner. That last pattern, a role grant followed within hours by Run Command use, is a strong signal of privilege escalation followed by execution.
Step 4: use Defender for Cloud alerts
Microsoft Defender for Cloud documents a set of alerts for Azure VM extensions based on Resource Manager operations. Several are marked preview. The ones most relevant here are:
| Alert type | What it describes | Severity |
|---|---|---|
VM_RunCommandSuspiciousScript | Run Command executed a script with parts identified as potentially malicious | High |
VM_RunCommandSuspiciousFailure | Failed, unauthorised and unusual Run Command attempt | Medium |
VM_RunCommandSuspiciousUsage | Run Command usage not commonly seen before | Low |
VM_CustomScriptExtensionSuspiciousCmd | Custom Script Extension ran a script with potentially malicious parts | High |
VM_CustomScriptExtensionUnusualDeletion | Unusual deletion of a Custom Script Extension, possibly clean-up | Medium |
VM_CustomScriptExtensionSuspiciousPayload | Custom Script Extension downloads a payload from a suspicious GitHub repository | Medium |
VM_VMAccessSuspiciousUsage | VMAccess used unusually to reset access or manage admin users | Medium |
VM_DSCExtensionSuspiciousScript | DSC extension deployed a script with potentially malicious parts | High |
VM_DiskEncryptionSuspiciousUsage | Unusual, high-volume disk encryption extension installs, possibly ransomware | Medium |
Do not downgrade the low-severity "unusual usage" alerts automatically. Low-severity alerts on Run Command from a new caller are often the earliest sign of an intrusion. Route them to triage with the identity context from Step 3 attached. Our Microsoft Defender for Cloud Guide covers plan enablement and alert routing.
Step 5: add host-side confirmation
Control plane events tell you that something ran. Host telemetry tells you what. Build host rules that look for:
- Scripts written by the Run Command or Custom Script Extension handlers that then download further payloads, add local users, change firewall or RDP settings, disable security tools or stop backup services.
- Credential access from processes descended from the guest agent, such as reads of local credential stores or memory of authentication processes.
- Requests from the VM to the Instance Metadata Service for managed identity tokens shortly after a Run Command, which suggests the attacker is pivoting from the VM into Azure with the VM's own identity.
- Run Command built-in IDs that weaken access controls:
DisableNLA,EnableAdminAccount,EnableRemotePSandSetRDPPort.
The managed identity point closes a loop that is easy to miss. An attacker with VM Contributor on one subscription can run code on a VM whose managed identity holds wider rights, then use that identity from inside the VM. Pair Run Command alerts with a check of the target VM's identity permissions; our guide on how to find over-privileged Azure managed identities covers the review.
Step 6: separate legitimate use from abuse
Most Run Command and extension activity is legitimate: patching, bootstrapping, monitoring agent installs and break-glass troubleshooting. Reduce false positives with:
- An automation register. List each service principal, managed identity and pipeline that is expected to use these operations, with the scopes it targets and the extensions it installs.
- Change windows. Correlate with change records. Run Command outside a change, by a human, on production deserves a question.
- Expected extensions. Keep a list of approved extension publishers and types per environment, and alert on anything else.
- Script content. For managed Run Command and Custom Script Extension, where script sources or URIs are recorded, alert on scripts fetched from public code hosting or file sharing sites outside an approved list.
Step 7: respond in the first hour
When an alert is confirmed or highly suspicious, work through these steps. Adapt them to your incident response plan.
- Identify the caller. From the Activity Log, record the caller object ID, type (user, service principal or managed identity), IP and authentication details.
- Contain the identity. For a user, revoke sessions and block sign-in. For a service principal, disable it or remove its credentials. For a managed identity used from a compromised VM, remove its role assignments or isolate the VM. Our Azure Subscription Compromise Playbook covers wider containment.
- Scope the blast radius. List every Run Command, extension write and role assignment by that caller across all subscriptions in the incident window.
- Preserve evidence. Snapshot affected disks, collect handler logs and endpoint telemetry, and export the relevant Activity Log entries before retention or attacker clean-up removes them.
- Remove persistence. Delete unexpected managed Run Commands and extensions, check for new local accounts and scheduled tasks, and review any credentials or tokens the VMs could reach.
- Check for pivots. Review the target VMs' managed identity activity and network connections to other hosts after the event.
Step 8: reduce the attack surface
Detection works best alongside fewer people and identities holding the rights in the first place:
- Limit
runCommand/action,runCommands/writeand extension write rights to the identities in your automation register, using custom roles instead of broad Contributor where practical. - Use just-in-time elevation for human administrators so Virtual Machine Contributor is not standing access.
- Restrict allowed extensions with Azure Policy and deny unapproved types in production.
- Replace client secrets on automation service principals with certificates or federated credentials, and alert on new credentials added to them.
- Review managed identities on VMs so a compromise of one host does not hand over a subscription.
Our Azure RBAC and Service Principals Guide and Azure Virtual Machines Security Guide cover these controls in depth.
Common failure patterns
- Host-only monitoring. Teams watch logons and network connections on VMs and miss code delivered by the platform agent.
- Activity Log not exported. Some subscriptions lack a diagnostic setting, so there is no central record of Run Command use.
- No caller baseline. Every Run Command looks the same in the SIEM because nobody recorded which identities are expected to use it.
- Ignoring low-severity alerts. "Unusual usage" alerts are auto-closed and the first sign of compromise is lost.
- Broad Contributor rights. Many identities hold Run Command rights indirectly through Contributor or Owner, making abuse easy and noise high.
- Missing the identity pivot. Responders clean the VM but do not check what its managed identity did afterwards.
- Scale sets forgotten. Detections cover VMs but not scale set model extension changes.
Practitioner checklist
- Export the Activity Log from every subscription to a central workspace and alert on diagnostic setting removal.
- Build an automation register of identities allowed to use Run Command and extensions.
- Deploy rules for new callers, fan-out across many VMs and unexpected extension writes and deletes.
- Join control plane hits with sign-in risk, new credentials and recent role assignments.
- Enable and route Defender for Cloud VM extension alerts, including low-severity ones.
- Collect Run Command handler logs and endpoint process telemetry from all VMs.
- Alert on Instance Metadata Service token requests following Run Command activity.
- Restrict Run Command and extension rights with custom roles and just-in-time access.
- Restrict allowed extension types with Azure Policy.
- Rehearse the first-hour response, including containment of service principals and managed identities.
Standards and references
- Microsoft Learn: Run scripts in your VM by using action and managed Run Commands
- Microsoft Learn: Action Run Command for Windows
- Microsoft Learn: Action Run Command for Linux
- Microsoft Learn: Azure virtual machine extensions and features
- Microsoft Learn: Alerts for Azure VM extensions
- MITRE ATT&CK (T1651 Cloud Administration Command)
- MITRE ATT&CK: Valid Accounts: Cloud Accounts
- NIST: SP 800-61 Rev. 3, Incident Response Recommendations and Considerations for Cybersecurity Risk Management
Related NHI Mgmt Group resources: T1651 Cloud Administration Command Defensive Guide · Azure Virtual Machines Security Guide · Azure Subscription Compromise Playbook · Storm-0501 Threat Actor Profile Guide