13 / 13Containers and serverless
Azure Functions security hardening
Harden Azure Functions: access keys and Entra auth, master key exposure, identity-based storage, network isolation, Flex Consumption, CORS and logging.
- Service
- Azure Functions
- Category
- Containers and serverless
- Baseline
- 11 controls
- Updated
On this page
Azure Functions runs event-driven code on the App Service platform: a function app is a Microsoft.Web/sites resource, so every App Service control (HTTPS, TLS, FTP, basic auth, access restrictions) applies, plus a set of risks specific to serverless. HTTP triggers are protected by shared access keys by default, not by identity, and a single master key grants administrative access to the runtime. Those keys live in the app's storage account, which by default is reached with an account key stored as a plain app setting, so read access to one storage account or one app setting is often enough to call every function or push code. Exposed function URLs with ?code= in logs and front-end code, storage accounts readable by too many identities, wildcard CORS and anonymous triggers are the recurring findings in assessments. This page maps to the Microsoft cloud security benchmark (MCSB) security baseline for Functions, the Function Apps section of the CIS Microsoft Azure Compute Services Benchmark, and the OWASP Serverless Top 10.
Baseline controls
Plain CIS numbers refer to the CIS Microsoft Azure Foundations Benchmark v7.0.0; numbers marked Compute refer to the CIS Microsoft Azure Compute Services Benchmark v2.0.1, and the Storage number to the CIS Microsoft Azure Storage Services Benchmark v2.0.0.
| Control | Why | How to check | ID |
|---|---|---|---|
| No anonymous HTTP triggers without platform auth | Keys are shared secrets, not identity | authLevel in function.json or code attributes, az webapp auth show | MCSB IM-1 / CIS Azure Compute 2.0.1 2.3.11 |
| Protect and isolate host and master keys | Master key grants admin runtime access | az functionapp keys list, functionsRuntimeAdminIsolationEnabled | MCSB IM-8 |
| Identity-based AzureWebJobsStorage | Removes the storage account key from app settings | AzureWebJobsStorage__credential present, no AccountKey= | MCSB IM-3 / CIS Compute 2.3.12 |
| Harden the function storage account | It holds keys and often the code | az storage account show --query "{shared:allowSharedKeyAccess, pna:publicNetworkAccess}" | MCSB NS-2 / CIS 9.2.1.1, CIS Azure Storage 2.0.0 16.1.7 |
| HTTPS, TLS 1.2, FTP and basic auth off | Same platform risks as App Service | az functionapp show --query httpsOnly | MCSB DP-3 / CIS Compute 2.3.3, 2.3.4, 2.3.6, 2.3.7 |
| Network isolation | Keep triggers and egress private | az functionapp vnet-integration list | MCSB NS-1, MCSB NS-2 / CIS Compute 2.3.13, 2.3.14, 2.3.16 |
| No wildcard CORS | * lets any site call your API from a browser | az functionapp cors show | CIS Compute 2.3.17 |
| Run from a read-only package | Prevents in-place code tampering | WEBSITE_RUN_FROM_PACKAGE or Flex deployment config | - |
| Application Insights with Entra auth | Telemetry keys allow injection of fake data | APPLICATIONINSIGHTS_AUTHENTICATION_STRING, DisableLocalAuth | MCSB LT-4 |
| Defender for App Service | Threat detection for apps on dedicated plans | az security pricing show -n AppServices | MCSB LT-1 / CIS 8.1.6.1 |
| Diagnostic logs and key access alerts | Detect key listing and secret reads | az monitor diagnostic-settings list --resource <app-id> | MCSB LT-4 / CIS 6.1.4 |
Function keys, authLevel and Entra authentication
Each HTTP trigger has an authLevel:
anonymous: no key required.function: a function key or a host key is required (?code=query string orx-functions-keyheader).admin: only the master key works.
Keys are 32-byte random strings with no identity, no expiry and no audit of who used them. They leak through browser developer tools, mobile app binaries, URLs in logs and proxies, and tickets. Treat function level as a speed bump, and put real authentication in front of anything that matters:
-
App Service Authentication with Entra ID on the function app, set to return 401 for unauthenticated callers. Service-to-service callers request a token for the app registration with their own managed identity. Function apps share the
Microsoft.Web/sitestype, so theaz webapp authcommands work on them:bashaz webapp auth microsoft update -g rg-func -n func-orders \ --client-id <app-registration-client-id> \ --issuer https://login.microsoftonline.com/<tenant-id>/v2.0 az webapp auth update -g rg-func -n func-orders --enabled true \ --unauthenticated-client-action Return401 -
Azure API Management in front, validating Entra tokens (
validate-jwt), applying rate limits, and calling the function with a key that clients never see. Restrict the function to the APIM outbound IP or subnet with access restrictions. -
Private endpoints, so the function is not reachable from the internet at all (see Network isolation).
authLevel: anonymous is acceptable only when one of these controls is in place, or for deliberate public webhooks that validate a provider signature in code. Review triggers in code review and in the deployed app:
az functionapp function list -g rg-func -n func-orders \
--query "[].{name:name, bindings:config.bindings[?type=='httpTrigger'].authLevel}" -o json
Use function-specific keys rather than host keys for each caller, so you can rotate one consumer without breaking others, and rotate explicitly when a key leaks: deleting and recreating a function with the same name reuses the old stored keys.
az functionapp function keys set -g rg-func -n func-orders \
--function-name CreateOrder --key-name partner-a
az functionapp keys set -g rg-func -n func-orders \
--key-type functionKeys --key-name default
Host and master keys
The master key (_master) is an administrative credential: it authorizes the /admin runtime APIs, and on apps with a writable file system that is enough to deploy and run code. Host keys call any function in the app. Three measures:
-
Disable the admin endpoints with the
functionsRuntimeAdminIsolationEnabledsite property. Requests to/adminare then refused even with the master key; management goes through Azure Resource Manager and RBAC instead. This property cannot be set on Linux Consumption apps.bashFUNC_ID=$(az functionapp show -g rg-func -n func-orders --query id -o tsv) az resource update --ids $FUNC_ID \ --set properties.functionsRuntimeAdminIsolationEnabled=true -
Move key storage to Key Vault. By default keys are stored as blobs in the
azure-webjobs-secretscontainer of theAzureWebJobsStorageaccount, so anyone with blob read access on that account can read every key. SetAzureWebJobsSecretStorageType=keyvaultandAzureWebJobsSecretStorageKeyVaultUri, use a dedicated vault per function app (secrets are not scoped per app inside a shared vault), and grant the app's identity a role that can manage secrets in that vault only.bashaz functionapp config appsettings set -g rg-func -n func-orders --settings \ AzureWebJobsSecretStorageType=keyvault \ AzureWebJobsSecretStorageKeyVaultUri=https://kv-func-orders.vault.azure.net/ -
Limit who can list keys.
Microsoft.Web/sites/host/listkeys/actionandMicrosoft.Web/sites/functions/listkeys/actionare included in Contributor and Website Contributor. Keep those roles to deployment pipelines and a small group, and alert on key listing (see Logging and detection). See Azure RBAC for custom roles.
Identity-based connection for AzureWebJobsStorage
Every function app needs a host storage account. The default AzureWebJobsStorage value is a connection string containing the account key, which is full control of the account, including the keys container described above. Replace it with a managed identity:
az functionapp identity assign -g rg-func -n func-orders \
--identities /subscriptions/<sub>/resourceGroups/rg-func/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id-func-orders
az functionapp config appsettings set -g rg-func -n func-orders --settings \
AzureWebJobsStorage__accountName=stfuncorders \
AzureWebJobsStorage__credential=managedidentity \
AzureWebJobsStorage__clientId=<user-assigned-client-id>
az functionapp config appsettings delete -g rg-func -n func-orders \
--setting-names AzureWebJobsStorage
Grant the identity Storage Blob Data Owner on the account (the documented minimum for the host), plus Storage Queue Data Contributor when you use blob or queue triggers and Storage Table Data Contributor for host diagnostic events. Scope the roles to that one storage account. Binding connections follow the same <CONNECTION_NAME>__credential pattern for Service Bus, Event Hubs, Cosmos DB and others.
Plan support differs:
| Hosting plan | Managed identity for host storage |
|---|---|
| Flex Consumption | Full support, no Azure Files dependency |
| Dedicated (App Service plan) | Full support |
| Elastic Premium, Consumption | Blobs, queues and tables; Azure Files content share still needs WEBSITE_CONTENTAZUREFILECONNECTIONSTRING, which you should store as a Key Vault reference |
Audit with Function apps should use managed identity. Secrets you cannot avoid belong in Key Vault references, as described on the App Service page.
The function storage account
The host storage account holds the access keys (unless moved to Key Vault), timer and trigger leases, Durable Functions state, and often the deployment package itself. Anyone who can write to it can change the code that runs. Harden it like any sensitive account (full guidance on Storage accounts):
- One storage account per function app, not shared with application data or other apps.
- Disable shared key access (
--allow-shared-key-access false) once the host, bindings and deployment all use identities. On Consumption and Elastic Premium apps that still use an Azure Files content share, shared key is still required unless you run without Azure Files. - Private endpoints and no public access. Create private endpoints for blob, queue and table (and file on Premium with a content share), with the matching
privatelinkDNS zones linked to the integrated VNet. The function app must have VNet integration to reach them. - No anonymous blob access, TLS 1.2 minimum, soft delete on blobs.
- Restrict data-plane roles. Storage Blob Data Reader on this account means reading the function keys.
az storage account update -g rg-func -n stfuncorders \
--allow-shared-key-access false --allow-blob-public-access false \
--min-tls-version TLS1_2 --public-network-access Disabled
HTTPS, TLS, FTP and basic auth
These settings are identical to App Service and are covered in detail on the App Service page. For function apps:
az functionapp update -g rg-func -n func-orders --set httpsOnly=true
az functionapp config set -g rg-func -n func-orders \
--min-tls-version 1.2 --ftps-state Disabled --remote-debugging-enabled false
for p in ftp scm; do
az resource update -g rg-func --name $p --namespace Microsoft.Web \
--resource-type basicPublishingCredentialsPolicies \
--parent sites/func-orders --set properties.allow=false
done
On Flex Consumption, FTP is not supported at all and ftpsState must not be set. Enforce across subscriptions with the Function app variants of the built-in policies: Function apps should only be accessible over HTTPS, Function apps should use the latest TLS version, Function apps should require FTPS only, Function apps should have local authentication methods disabled for FTP deployments, Function apps should have local authentication methods disabled for SCM site deployments and Function apps should have remote debugging turned off, with their "Configure Function apps to ..." remediation counterparts and the separate slot policies. See Azure Policy for assignment at management group scope.
Network isolation
Choose a plan that supports networking
The hosting plan decides what isolation is possible:
- Flex Consumption is Linux-only and Microsoft's recommended serverless plan. It supports VNet integration, private endpoints and per-app identity-based deployment storage. It does not support deployment slots, and one app runs per plan.
- Consumption (Linux) gets no new features or language versions since 30 September 2025 and is retired on 30 September 2028. It has no VNet support. Migrate to Flex Consumption with
az functionapp flex-migrationor by creating a new app and redeploying; in-place plan changes are not supported. Windows Consumption is not affected by the retirement, but it also has no VNet integration. - Elastic Premium and Dedicated support VNet integration and private endpoints, with
vnetRouteAllEnabledto send all egress through the VNet.
Inbound and outbound
Inbound, add a private endpoint (group ID sites) and disable public network access, or restrict access to APIM or Front Door with access restrictions. Outbound, integrate the app with a subnet so it reaches private endpoints on storage, Key Vault and databases. For Flex Consumption, the subnet must be delegated to Microsoft.App/environments and be at least /27; networking is configured on the app, not through app settings such as WEBSITE_VNET_ROUTE_ALL or WEBSITE_CONTENTOVERVNET, which Flex ignores.
az network vnet subnet update -g rg-net --vnet-name vnet-spoke -n snet-func \
--delegations Microsoft.App/environments
az functionapp create -g rg-func -n func-orders --storage-account stfuncorders \
--flexconsumption-location westeurope --runtime python --runtime-version 3.12 \
--vnet <vnet-resource-id> --subnet snet-func \
--deployment-storage-name stfuncorders --deployment-storage-container-name app-package \
--deployment-storage-auth-type UserAssignedIdentity \
--deployment-storage-auth-value <user-assigned-identity-resource-id> \
--domain-name-scope TenantReuse
az resource update --ids $FUNC_ID --set properties.publicNetworkAccess=Disabled
Remember the SCM site: with access restrictions instead of a private endpoint, apply them to the SCM site too. Event sources follow the same rule: a Service Bus or Event Hubs namespace behind a private endpoint needs the function's integrated subnet to resolve its private DNS. Enforce inbound isolation with Function apps should disable public network access. NSG, route table and firewall patterns are on Virtual Network.
CORS
CORS controls which browser origins can call your HTTP triggers with JavaScript. A wildcard (*) lets any website, including a malicious one visited by your users, call the API from their browser. List exact origins, and enable credentials support only when you need cookies or auth headers to flow cross-origin.
az functionapp cors show -g rg-func -n func-orders
az functionapp cors remove -g rg-func -n func-orders --allowed-origins "*"
az functionapp cors add -g rg-func -n func-orders \
--allowed-origins https://portal.contoso.com
Audit with Function apps should not have CORS configured to allow every resource to access your apps.
Run from package
When code is deployed as files into wwwroot, anyone with write access to the file system (Kudu, FTP, a compromised dependency writing to disk) can change it in place. Running from a package mounts a read-only zip:
- Consumption, Elastic Premium, Dedicated: set
WEBSITE_RUN_FROM_PACKAGE=1with zip deploy, or a URL to a package in a private blob container. Prefer Entra ID access with a managed identity over a SAS in the URL; with a user-assigned identity also setWEBSITE_RUN_FROM_PACKAGE_BLOB_MI_RESOURCE_ID. - Flex Consumption: always runs from a package in the deployment blob container;
WEBSITE_RUN_FROM_PACKAGEis not used. Configure the deployment storage with--deployment-storage-auth-type UserAssignedIdentityorSystemAssignedIdentityinstead of a connection string.
az functionapp deployment config set -g rg-func -n func-orders \
--deployment-storage-auth-type UserAssignedIdentity \
--deployment-storage-auth-value <user-assigned-identity-resource-id>
Whoever can write to the package container controls the code. Keep write access on that container to the deployment pipeline identity.
Application Insights with Entra authentication
By default, telemetry is sent with the connection string's instrumentation key, which is not a secret: anyone who finds it can send fake telemetry and pollute or hide signals. Switch ingestion to Entra ID and disable local authentication on the Application Insights resource:
az functionapp config appsettings set -g rg-func -n func-orders --settings \
"APPLICATIONINSIGHTS_AUTHENTICATION_STRING=ClientId=<user-assigned-client-id>;Authorization=AAD"
AI_ID=$(az resource show -g rg-func -n appi-func-orders \
--resource-type Microsoft.Insights/components --query id -o tsv)
az role assignment create --assignee <user-assigned-principal-id> \
--assignee-principal-type ServicePrincipal \
--role "Monitoring Metrics Publisher" --scope $AI_ID
az resource update --ids $AI_ID --set properties.DisableLocalAuth=true
Use Authorization=AAD alone for the system-assigned identity. Make sure the workspace behind Application Insights is governed like the rest of your logging (see Azure Monitor), and do not log request bodies, tokens or keys from function code.
Defender for App Service coverage
Microsoft Defender for App Service covers function apps that run in a dedicated (App Service) plan: when the plan is enabled on a subscription, those apps get detections for scanners, suspicious process execution, malicious IPs connecting to FTP and dangling DNS, billed per App Service plan instance. Microsoft's Functions security guidance documents these enhanced protections only for dedicated plans, so do not count on Defender for App Service for Consumption or Flex Consumption apps; rely on the platform controls on this page and on Defender for Storage for the host storage account instead.
az security pricing create -n AppServices --tier Standard
Enable it from Defender for Cloud, and also consider Defender for Storage on the host storage account, which detects unusual access to blobs such as the keys container.
Logging and detection
Send FunctionAppLogs to a central Log Analytics workspace with a diagnostic setting, alongside Application Insights for request and dependency telemetry. Enforce with Function apps should have resource logs enabled or Enable logging by category group for Function App (microsoft.web/sites) to Log Analytics.
az monitor diagnostic-settings create --name to-law --resource $FUNC_ID \
--workspace <log-analytics-workspace-id> \
--logs '[{"category":"FunctionAppLogs","enabled":true}]'
Alert on reads of keys and app settings through the control plane. Each of these returns secrets:
AzureActivity
| where TimeGenerated > ago(1d)
| where OperationNameValue in~ (
"MICROSOFT.WEB/SITES/HOST/LISTKEYS/ACTION",
"MICROSOFT.WEB/SITES/FUNCTIONS/LISTKEYS/ACTION",
"MICROSOFT.WEB/SITES/CONFIG/LIST/ACTION",
"MICROSOFT.WEB/SITES/BASICPUBLISHINGCREDENTIALSPOLICIES/WRITE")
| where Caller !in ("<pipeline-identity-object-id>")
| project TimeGenerated, Caller, CallerIpAddress, OperationNameValue, _ResourceId
With blob diagnostic logs enabled on the host storage account, catch direct reads of the stored keys:
StorageBlobLogs
| where TimeGenerated > ago(1d)
| where Uri has "azure-webjobs-secrets" and OperationName == "GetBlob"
| summarize Reads = count() by AccountName, RequesterObjectId, CallerIpAddress, AuthenticationType
Watch for unhandled errors and host-level warnings that often accompany probing or failed exploitation:
FunctionAppLogs
| where TimeGenerated > ago(1h)
| where Level in ("Error", "Warning")
| summarize Events = count() by _ResourceId, FunctionName, Category
| order by Events desc
Activity log alert rules, workspace design and retention are covered on Azure Monitor.
Common mistakes
- Shipping function keys in front-end or mobile code. The key is extracted in minutes and grants the same access to anyone; there is no way to tell legitimate callers apart.
- Leaving
AzureWebJobsStorageas an account key connection string. Anyone who can read app settings gets full control of the storage account, including the stored function keys and possibly the deployment package. - Granting Storage Blob Data Reader on the host storage account to "read logs". That role also reads the
azure-webjobs-secretscontainer, which holds the master key. - Wildcard CORS on an API that uses cookies or Easy Auth. Any website can make authenticated cross-origin calls on behalf of a signed-in user.
- Starting new apps on Linux Consumption. No VNet support, no new language versions since September 2025, and a forced migration before 30 September 2028.
- Private endpoint on the function but not on its storage account. The code and keys stay reachable over the internet through the storage endpoint.
- Assuming deleting a function revokes its key. A recreated function with the same name reuses the stored key; rotate explicitly.
References
- Securing Azure Functions (Microsoft Learn)
- Azure security baseline for Functions (Microsoft Learn)
- Work with access keys in Azure Functions (Microsoft Learn)
- Configure connections to remote services in Azure Functions (Microsoft Learn)
- Azure Functions Flex Consumption plan hosting (Microsoft Learn)
- Azure Functions Consumption plan hosting (Microsoft Learn)
- Azure Functions networking options (Microsoft Learn)
- Storage considerations for Azure Functions (Microsoft Learn)
- Microsoft Entra authentication for Application Insights (Microsoft Learn)
- OWASP Serverless Top 10 (OWASP)
- CIS Microsoft Azure Foundations Benchmark (Center for Internet Security)
Filed under azure-functions, serverless, paas, 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.