05 / 13Governance and logging
Azure Monitor and Log Analytics security hardening
Harden Azure Monitor and Log Analytics: activity and Entra log export, diagnostic settings at scale, workspace access, retention, log protection, alerts.
- Service
- Azure Monitor
- Category
- Governance and logging
- Baseline
- 10 controls
- Updated
On this page
Azure Monitor is the platform that collects Azure's logs and metrics, and Log Analytics is the workspace where they are stored and queried with KQL. Azure keeps less than most people assume: the activity log is retained for 90 days, Microsoft Entra sign-in and audit logs for 7 to 30 days depending on licence, and resource logs (Key Vault access, storage reads, firewall decisions) are not collected at all until you create a diagnostic setting. Incidents are routinely discovered months after initial access, and by then the evidence is gone unless you exported it. Attackers know this too: deleting diagnostic settings and tampering with logs is a documented technique (MITRE ATT&CK T1562.008, Disable or Modify Cloud Logs). And a workspace that holds every sign-in in the tenant is itself sensitive data that needs access control. This page maps to the Logging and Threat Detection (LT) domain of the Microsoft cloud security benchmark (MCSB) and to the Logging and Monitoring section of the CIS Microsoft Azure Foundations Benchmark.
Baseline controls
CIS numbers refer to the CIS Microsoft Azure Foundations Benchmark v7.0.0.
| Control | Why | How to check | ID |
|---|---|---|---|
| Central security workspace | One place to query and correlate every source | az monitor log-analytics workspace list -o table | MCSB LT-5 |
| Activity log exported per subscription | Control plane history beyond 90 days | az monitor diagnostic-settings subscription list | MCSB LT-3 / CIS 6.1.1.1, 6.1.1.2 |
| Resource logs through policy | Data plane activity is not collected by default | Compliance of the audit category group initiative | MCSB LT-3 / CIS 6.1.4 |
| Entra sign-in and audit logs exported | Identity is where most intrusions start | Entra admin center > Diagnostic settings | MCSB LT-2 / CIS 6.1.1.7, 6.1.1.8 |
| Azure Monitor Agent with DCRs | OS security events from VMs, legacy agent is retired | az vm extension list for AzureMonitorWindowsAgent | MCSB LT-3 |
| Workspace access control | Logs contain sign-ins, IPs and sometimes secrets | Workspace enableLogAccessUsingOnlyResourcePermissions | MCSB PA-7 |
| Retention of one year or more | Investigations reach back months | az monitor log-analytics workspace table show | MCSB LT-6 |
| Logs protected from deletion and change | Tampering hides the attacker | az lock list -g <rg>, immutability policy | MCSB LT-6 / CIS 6.2 |
| Private ingestion and query | Keeps telemetry and queries off the public internet | publicNetworkAccessForIngestion property | MCSB NS-2 / CIS 6.1.6 |
| CIS activity log alerts | Immediate signal on risky control plane changes | az monitor activity-log alert list | CIS 6.1.2.1 to 6.1.2.17 |
Central Log Analytics workspace
Put the security workspace in a dedicated platform subscription (for example management), in its own resource group, in a region that fits your data residency requirements. One workspace per tenant (or per region when regulation requires it) beats a workspace per team: detections need to join SigninLogs with AzureActivity with Key Vault AuditEvent, and cross-workspace queries are slower and easier to get wrong.
az group create --name rg-management-logs --location westeurope
az monitor log-analytics workspace create \
--resource-group rg-management-logs \
--workspace-name law-security-weu \
--location westeurope \
--retention-time 365
If you run Microsoft Sentinel, enable it on this workspace. Application teams can keep their own operational workspaces for performance data; security-relevant logs go to the central one, and diagnostic settings can send to both.
Activity log export
The activity log records control plane operations: resource creation and deletion, role assignments, policy changes, network rule changes. Create one diagnostic setting per subscription that sends every category to the workspace:
WS=$(az monitor log-analytics workspace show -g rg-management-logs -n law-security-weu --query id -o tsv)
az monitor diagnostic-settings subscription create \
--name activity-to-law \
--location westeurope \
--workspace "$WS" \
--logs '[
{"category":"Administrative","enabled":true},
{"category":"Security","enabled":true},
{"category":"ServiceHealth","enabled":true},
{"category":"Alert","enabled":true},
{"category":"Recommendation","enabled":true},
{"category":"Policy","enabled":true},
{"category":"Autoscale","enabled":true},
{"category":"ResourceHealth","enabled":true}
]'
az monitor diagnostic-settings subscription list --query "value[].{name:name, ws:workspaceId}" -o table
Records land in the AzureActivity table. Portal path: Monitor > Activity log > Export Activity Logs.
For every subscription, current and future, assign the built-in policy Configure Azure Activity logs to stream to specified Log Analytics workspace (DeployIfNotExists) at your top management group, with a managed identity and a remediation task. The audit counterpart Azure Monitor should collect activity logs from all regions surfaces gaps. Rollout patterns are on the Azure Policy page. Legacy log profiles are deprecated; use diagnostic settings for every new export.
Diagnostic settings at scale
Resource logs record what happens inside a resource. They are off until a diagnostic setting exists. Settings support category groups: audit (the security-relevant subset) and allLogs (everything).
az monitor diagnostic-settings create \
--name kv-to-law \
--resource <key-vault-resource-id> \
--workspace "$WS" \
--logs '[{"categoryGroup":"audit","enabled":true}]'
Per resource does not scale. Assign the built-in initiative Enable audit category group resource logging for supported resources to Log Analytics at your top management group, with a managed identity that has Log Analytics Contributor and Monitoring Contributor rights, then run remediation. Use Enable allLogs category group resource logging for supported resources to Log Analytics selectively, where you need full detail, because volume and cost grow quickly.
Priority resources:
- Key Vault:
AuditEventrecords every secret, key and certificate access (see Key Vault). - Storage accounts holding sensitive data:
StorageRead,StorageWrite,StorageDeleteper service (see Storage accounts). - Azure Firewall and WAF: network, application, threat intelligence and IDPS logs (see Virtual Network).
- SQL: auditing to the workspace (see SQL Database).
- AKS:
kube-audit-adminandguard(see AKS).
Diagnostic settings are extension resources, so Resource Graph does not list them next to their parent resources. The compliance view of the initiative is the simplest coverage report. For a spot check from the CLI:
for KV in $(az keyvault list --query "[].id" -o tsv); do
N=$(az monitor diagnostic-settings list --resource "$KV" --query "length(value)" -o tsv 2>/dev/null || echo 0)
[ "$N" = "0" ] && echo "No diagnostic setting: $KV"
done
Microsoft Entra logs export
In the Entra admin center, go to Entra ID > Monitoring and health > Diagnostic settings and send these categories to the same workspace:
AuditLogs,SignInLogs,NonInteractiveUserSignInLogsServicePrincipalSignInLogs,ManagedIdentitySignInLogsProvisioningLogsRiskyUsers,UserRiskEvents,RiskyServicePrincipals,ServicePrincipalRiskEvents(Entra ID P2)MicrosoftGraphActivityLogs
Exporting sign-in logs requires Microsoft Entra ID P1 or P2. Non-interactive and service principal sign-ins are where token replay and abused app credentials show up, so do not drop them to save cost. MicrosoftGraphActivityLogs records Graph API requests across the tenant and is the best source for spotting mailbox or directory enumeration by a compromised application.
The setting lives at the tenant-level microsoft.aadiam provider and can be created with ARM:
az rest --method PUT \
--url "https://management.azure.com/providers/microsoft.aadiam/diagnosticSettings/entra-to-law?api-version=2017-04-01" \
--body "{\"properties\":{\"workspaceId\":\"$WS\",\"logs\":[{\"category\":\"AuditLogs\",\"enabled\":true},{\"category\":\"SignInLogs\",\"enabled\":true},{\"category\":\"NonInteractiveUserSignInLogs\",\"enabled\":true},{\"category\":\"ServicePrincipalSignInLogs\",\"enabled\":true},{\"category\":\"ManagedIdentitySignInLogs\",\"enabled\":true},{\"category\":\"MicrosoftGraphActivityLogs\",\"enabled\":true}]}}"
Creating it requires Security Administrator in Entra ID plus write access to the workspace. Identity hardening itself is on the Entra ID page.
Azure Monitor Agent and data collection rules
The legacy Log Analytics agent (MMA/OMS) was retired in August 2024. The Azure Monitor Agent (AMA) replaces it and is configured through data collection rules (DCRs) that say what to collect and where to send it. A DCR for Windows security events sends to the SecurityEvent table; Linux syslog goes to Syslog.
Deploy the agent and associate DCRs through policy rather than per VM:
- Configure Windows virtual machines to run Azure Monitor Agent using system-assigned managed identity
- Configure Linux virtual machines to run Azure Monitor Agent with system-assigned managed identity-based authentication
- Configure Windows Virtual Machines to be associated with a Data Collection Rule or a Data Collection Endpoint
- Configure Linux Virtual Machines to be associated with a Data Collection Rule or a Data Collection Endpoint
Equivalent definitions exist for scale sets and Arc-enabled machines. Verify on a VM:
az vm extension list -g <rg> --vm-name <vm> \
--query "[?contains(name,'AzureMonitor')].{name:name, state:provisioningState}" -o table
az monitor data-collection rule association list --resource <vm-resource-id> -o table
DCRs are now a security control: who can edit them can silently stop collection. Restrict Microsoft.Insights/dataCollectionRules/write to the platform team, and enable diagnostic logs on DCRs themselves if you need to detect ingestion errors. VM hardening is on the Virtual Machines page.
Workspace access control
A security workspace contains every sign-in, caller IP and often request bodies. Treat read access as privileged.
Access control mode. Set the workspace to "Use resource or workspace permissions" (enableLogAccessUsingOnlyResourcePermissions: true, the default since 2019). Application teams then query logs of resources they can read, in resource context, without being granted the workspace. Check and fix older workspaces:
az monitor log-analytics workspace show -g rg-management-logs -n law-security-weu \
--query "features.enableLogAccessUsingOnlyResourcePermissions"
az resource update --ids "$WS" \
--set properties.features.enableLogAccessUsingOnlyResourcePermissions=true
Workspace roles. Give the security team Log Analytics Reader (or the narrower Log Analytics Data Reader) on the workspace, assigned at the workspace scope. Log Analytics Contributor is powerful: it can add VM extensions, which Microsoft documents as a path to full control of a VM, and it can change diagnostic settings. Keep it for the platform team.
Table and row level access. Microsoft now recommends granular RBAC, which uses Azure ABAC conditions on role assignments of the Log Analytics Data Reader role to restrict access to specific tables or rows. Use it, for example, to let a SOC tier 1 read SecurityAlert but not SigninLogs, or to isolate HR application logs. The older table-level method (custom roles with Microsoft.OperationalInsights/workspaces/query/<table>/read) still works but should not be used for new designs. For particularly sensitive tables, the protected tables feature (preview) makes access deny-by-default.
Retention
Workspace retention applies to all tables unless overridden, and each table can also have a total retention (interactive plus long-term) of up to 12 years. Keep at least one year interactive for AzureActivity, SigninLogs, AuditLogs and Key Vault logs; regulations may ask for more.
az monitor log-analytics workspace table update \
-g rg-management-logs --workspace-name law-security-weu \
--name SigninLogs --retention-time 365 --total-retention-time 1095
az monitor log-analytics workspace table show \
-g rg-management-logs --workspace-name law-security-weu \
--name SigninLogs --query "{interactive:retentionInDays, total:totalRetentionInDays}"
The audit policy Activity log should be retained for at least one year checks the activity log side. Long-term retention is cheaper per GB and can be queried with search jobs or restored when an investigation needs it.
Protecting the logs
Logs are only evidence if an attacker with a stolen admin token cannot remove them.
- Resource locks. Put a
CanNotDeletelock on the workspace resource group and on archive storage accounts. A lock does not stop a determined Owner, but it forces a separate, logged, alertable step.
az lock create --name protect-law --lock-type CanNotDelete --resource-group rg-management-logs
- Immutable archive. Send a second copy of the activity log and Entra logs to a storage account in a separate subscription, with a time-based retention policy on the containers (WORM). Once locked, nobody can delete or modify the blobs before expiry, including subscription owners.
az storage container immutability-policy create \
--account-name stlogarchive --container-name insights-activity-logs \
--period 365
az storage container immutability-policy lock \
--account-name stlogarchive --container-name insights-activity-logs \
--if-match "<etag>"
- Purge rights. Data purge in Log Analytics requires the Data Purger role. Nobody should hold it permanently; grant it through PIM for privacy requests only.
- Separation of duties. The people whose activity is logged (subscription Owners, platform engineers) should not be the only administrators of the log platform.
Network isolation of the workspace
By default a workspace accepts ingestion and queries from the public internet. With an Azure Monitor Private Link Scope (AMPLS), agents send data over private endpoints and you can block public ingestion and querying. Use the policies "Log Analytics workspaces should block log ingestion and querying from public networks" and "Log Analytics Workspaces should block non-Azure Active Directory based ingestion." to enforce Entra-authenticated, private-only access. Plan DNS carefully: AMPLS changes resolution of shared global endpoints for every client in the linked VNets, so roll it out at the hub, not per spoke.
Activity log alerts
The CIS benchmark lists activity log alerts every subscription should have (6.1.2.1 to 6.1.2.17). Create them as activity log alert rules sending to an action group. The loop below covers 6.1.2.1 to 6.1.2.10; the benchmark also asks for alerts on Service Health, role assignment create and delete, policy exemptions, diagnostic setting and resource lock deletion, and Key Vault access policy updates (6.1.2.11 to 6.1.2.17):
az monitor action-group create -g rg-management-logs -n ag-security \
--short-name secops --action email secops secops@example.com
for OP in \
Microsoft.Authorization/policyAssignments/write \
Microsoft.Authorization/policyAssignments/delete \
Microsoft.Network/networkSecurityGroups/write \
Microsoft.Network/networkSecurityGroups/delete \
Microsoft.Security/securitySolutions/write \
Microsoft.Security/securitySolutions/delete \
Microsoft.Sql/servers/firewallRules/write \
Microsoft.Sql/servers/firewallRules/delete \
Microsoft.Network/publicIPAddresses/write \
Microsoft.Network/publicIPAddresses/delete
do
NAME="ala-$(echo "$OP" | tr '/.' '--' | tr 'A-Z' 'a-z' | cut -c1-60)"
az monitor activity-log alert create -g rg-management-logs -n "$NAME" \
--scopes /subscriptions/<sub-id> \
--condition "category=Administrative and operationName=$OP" \
--action-group ag-security
done
Audit coverage with the policies "An activity log alert should exist for specific Administrative operations", "An activity log alert should exist for specific Policy operations" and "An activity log alert should exist for specific Security operations".
Logging and detection
Activity log alerts are cheap but narrow. Add scheduled log search alerts (or Sentinel analytics rules) on the workspace for the techniques that target the logging pipeline and privileged access:
// Diagnostic settings deleted or changed: logging tampering (T1562.008)
AzureActivity
| where OperationNameValue has "MICROSOFT.INSIGHTS/DIAGNOSTICSETTINGS"
| where OperationNameValue endswith "DELETE" or OperationNameValue endswith "WRITE"
| where ActivityStatusValue == "Success"
| project TimeGenerated, Caller, CallerIpAddress, _ResourceId, OperationNameValue
// Workspace, DCR or retention changes
AzureActivity
| where OperationNameValue has_any ("MICROSOFT.OPERATIONALINSIGHTS/WORKSPACES/DELETE",
"MICROSOFT.OPERATIONALINSIGHTS/WORKSPACES/TABLES/WRITE",
"MICROSOFT.INSIGHTS/DATACOLLECTIONRULES/WRITE",
"MICROSOFT.INSIGHTS/DATACOLLECTIONRULES/DELETE",
"MICROSOFT.AUTHORIZATION/LOCKS/DELETE")
| where ActivityStatusValue == "Success"
| project TimeGenerated, Caller, CallerIpAddress, _ResourceId, OperationNameValue
// Owner or User Access Administrator granted (T1098)
AzureActivity
| where OperationNameValue =~ "MICROSOFT.AUTHORIZATION/ROLEASSIGNMENTS/WRITE"
| where ActivityStatusValue == "Success"
| extend roleDef = tostring(parse_json(tostring(parse_json(Properties).requestbody)).Properties.RoleDefinitionId)
| where roleDef has_any ("8e3af657-a8ff-443c-a75c-2fe8c4bcb635", "18d7d88d-d35e-4fb5-a5c3-7773c20a72d9")
| project TimeGenerated, Caller, CallerIpAddress, _ResourceId
// A log source went silent
union withsource=SourceTable AzureActivity, SigninLogs, AuditLogs, AzureDiagnostics
| where TimeGenerated > ago(7d)
| summarize LastRecord = max(TimeGenerated) by SourceTable
| where LastRecord < ago(2h)
The workspace's own query audit (LAQueryLogs, via a diagnostic setting on the workspace) shows who searched what, which is useful when logs themselves may have been read by an intruder. Defender for Cloud alerts flow into the same workspace through continuous export (see Defender for Cloud).
Common mistakes
- Relying on the 90 day activity log. Without export, a breach found in month four has no control plane history.
- Diagnostic settings created by hand. Every new resource is unlogged until someone remembers. Assign the
auditcategory group initiative withDeployIfNotExists. - Dropping non-interactive and service principal sign-ins to save cost. Those are exactly the logs that show token replay and stolen app secrets.
- Granting Log Analytics Contributor broadly. It allows VM extension deployment and diagnostic setting changes, which means code execution on VMs and the ability to switch logging off.
- Workspace in the same subscription as the workloads, with no lock. A compromised subscription Owner deletes the evidence in one call.
- Still running the legacy Log Analytics agent. It has been retired since August 2024 and no longer receives support; machines on it can stop sending data without anyone noticing.
- No alert on silent sources. A deleted diagnostic setting looks exactly like a quiet day unless you monitor ingestion.
References
- Azure Monitor activity log (Microsoft Learn)
- Diagnostic settings in Azure Monitor (Microsoft Learn)
- Integrate Microsoft Entra logs with Azure Monitor logs (Microsoft Learn)
- Manage access to Log Analytics workspaces (Microsoft Learn)
- Granular RBAC in Azure Monitor Logs (Microsoft Learn)
- Manage data retention in a Log Analytics workspace (Microsoft Learn)
- Azure Monitor Agent overview (Microsoft Learn)
- Use Azure Private Link to connect networks to Azure Monitor (Microsoft Learn)
- Immutable storage for Azure Blob Storage (Microsoft Learn)
- Azure security baseline for Azure Monitor (Microsoft Learn)
- T1562.008: Disable or Modify Cloud Logs (MITRE ATT&CK)
- CIS Microsoft Azure Foundations Benchmark (Center for Internet Security)
Filed under azure-monitor, logging, detection, cis-benchmark
Written by
Florian Amette, Cloud Security Engineer & EditorSecurity engineer writing practical hardening pages for Microsoft Azure tenants and subscriptions, aligned with the CIS Microsoft Azure Foundations Benchmark.