# Azure Pentesting

{{#include ../../banners/hacktricks-training.md}}

## Basic Information

Learn the basics of Azure and Entra ID in the following page:

{{#ref}}
az-basic-information/
{{#endref}}

## Azure Pentester/Red Team Methodology

In order to audit an AZURE environment it's very important to know: which **services are being used**, what is **being exposed**, who has **access** to what, and how are internal Azure services and **external services** connected.

From a Red Team point of view, the **first step to compromise an Azure environment** is to manage to obtain some **foothold**.

### External enum & Initial Access

The first step is of course to enumerate information about the tenant you are attacking and try to get a foothold.

Based on the domain name it's possible to know **if the company if using Azure**, get the **tenant ID**, get other **valid domains** in the same tenant (if more) and get **relevant information** like if SSO is enabled, mail configurations, valid user emails...

Check the following page to learn how to perform the **external enumeration**:

{{#ref}}
az-unauthenticated-enum-and-initial-entry/
{{#endref}}

With this information the most common ways to try to get a foothold are:
- **OSINT**: Check for **leaks** in Github or any other open source platform that could contain **credentials** or interesting information.
- **Password** reuse, leaks or [password spraying](az-unauthenticated-enum-and-initial-entry/az-password-spraying.md)
  - Buy credentials to an employee
- [**Common Phishing**](https://book.hacktricks.wiki/en/generic-methodologies-and-resources/phishing-methodology/index.html) (credentials or Oauth App)
  - [Device Code Authentication Phishing](az-unauthenticated-enum-and-initial-entry/az-device-code-authentication-phishing.md)
- 3rd parties **breached**
- Vulnerabilities in Azure-Hosted Applications
  - [**Server Side Request Forgery**](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html) with access to metadata endpoint
  - **Subdomain takeovers** like in [https://godiego.co/posts/STO-Azure/](https://godiego.co/posts/STO-Azure/)
  - **Other azure services misconfigurations**
- If some developer laptop is compromised ([WinPEAS and LinPEAS](https://github.com/peass-ng/PEASS-ng) can find this info):
  - Inside **`<HOME>/.Azure`**
    - **`azureProfile.json`** contains info about logged in users from the past
    - **`clouds.config contains`** info about subscriptions
    - **`service_principal_entries.json`** contains applications credentials (tenant id, clients and secret). Only in Linux & macOS
    - **`msal_token_cache.json`** contains contains access tokens and refresh tokens. Only in Linux & macOS 
    - **`service_principal_entries.bin`** and msal_token_cache.bin are used in Windows and are encrypted with DPAPI
    - **`msal_http_cache.bin`** is a cache of HTTP request
      - Load it: `with open("msal_http_cache.bin", 'rb') as f: pickle.load(f)`
    - **`AzureRmContext.json`** contains information about previous logins using Az PowerShell (but no credentials)
  - Inside **`C:\Users\<username>\AppData\Local\Microsoft\IdentityCache\*`** are several `.bin` files with **access tokens**, ID tokens and account information encrypted with the users DPAPI.
  - It’s possible to find more **access tokens** in the `.tbres` files inside **`C:\Users\<username>\AppData\Local\Microsoft\TokenBroken\Cache\`** which contain a base64 encrypted with DPAPI with access tokens.
  - In Linux and macOS you can get **access tokens, refresh tokens and id tokens** from Az PowerShell (if used) running `pwsh -Command "Save-AzContext -Path /tmp/az-context.json"`
    - In Windows this just generates id tokens.
    - Possible to see if Az PowerShell was used in Linux and macSO checking is `$HOME/.local/share/.IdentityService/` exists (although the contained files are empty and useless)

Find **other Azure Services misconfigurations** that cal lead to a foothold in the following page:

{{#ref}}
az-unauthenticated-enum-and-initial-entry/
{{#endref}}

> [!NOTE]
> Remember that usually the **noisiest** part of the enumeration is the **login**, not the enumeration itself.

### Azure & Entra ID tooling

The following tools will be super useful to enumerate both Entra ID tenants and Azure environments slowly (to avoid detection) or automatically (to save time):

{{#ref}}
az-enumeration-tools.md
{{#endref}}

### Bypass Access Policies

<figure><img src="../../images/image (268).png" alt=""><figcaption></figcaption></figure>

In cases where you have some valid credentials but you cannot login, these are some common protections that could be in place:

- **IP whitelisting** -- You need to compromise a valid IP
- **Geo restrictions** -- Find where the user lives or where are the offices of the company and get a IP from the same city (or contry at least)
- **Browser** -- Maybe only a browser from certain OS (Windows, Linux, Mac, Android, iOS) is allowed. Find out which OS the victim/company uses.
- You can also try to **compromise Service Principal credentials** as they usually are less limited and its login is less reviewed

After bypassing it, you might be able to get back to your initial setup and you will still have access.

Check:

{{#ref}}
az-privilege-escalation/az-entraid-privesc/az-conditional-access-policies-mfa-bypass.md
{{#endref}}

### Whoami

> [!CAUTION]
> Learn **how to install** az cli, AzureAD and Az PowerShell in the [**Az - Entra ID**](az-services/az-azuread.md) section.

One of the first things you need to know is **who you are** (in which environment you are):

{{#tabs }}
{{#tab name="az cli" }}

```bash
az account list
az account tenant list # Current tenant info
az account subscription list # Current subscription info
az ad signed-in-user show # Current signed-in user
az ad signed-in-user list-owned-objects # Get owned objects by current user
az account management-group list #Not allowed by default
```

{{#endtab }}

{{#tab name="Az" }}

```bash
# Get the information about the current context (Account, Tenant, Subscription etc.)
Get-AzContext
# List all available contexts
Get-AzContext -ListAvailable
# Enumerate subscriptions accessible by the current user
Get-AzSubscription
#Get Resource group
Get-AzResourceGroup
```

{{#endtab }}

{{#tab name="Mg" }}

```bash
#Get the current session
Get-MgContext
```

{{#endtab }}

{{#tab name="AzureAD" }}

```bash
#Get the current session state
Get-AzureADCurrentSessionInfo
#Get details of the current tenant
Get-AzureADTenantDetail
```

{{#endtab }}
{{#endtabs }}


### Entra ID Enumeration & Privesc

By default, any user should have **enough permissions to enumerate** things such as users, groups, roles, service principals... (check [default AzureAD permissions](az-basic-information/index.html#default-user-permissions)).\
You can find here a guide:

{{#ref}}
az-services/az-azuread.md
{{#endref}}

Check the **Post-Exploitation tools** to find tools to escalate privileges in Entra ID like **AzureHound:**

{{#ref}}
az-enumeration-tools.md#automated-post-exploitation-tools
{{#endref}}


### Azure Enumeration

Once you know who you are, you can start enumerating the **Azure services you have access to**.

You should start finding out the **permissions you have** over the resources. For this:

1. **Find the resource you have some acecss to**:

> [!TIP]
> This doesn't require any special permission.

The Az PoswerShell command **`Get-AzResource`** lets you **know the resources your current user has visibility over**.

Moreover, you can get the same info in the **web console** going to [https://portal.azure.com/#view/HubsExtension/BrowseAll](https://portal.azure.com/#view/HubsExtension/BrowseAll) or searching for "All resources" or executing: 
```bash
az rest --method GET --url "https://management.azure.com/subscriptions/<subscription-id>/resources?api-version=2021-04-01"
```

2. **Find the permissions you have over the resources you can see**:

> [!TIP]
> This doesn't require any special permission.

Talking to the API **`https://management.azure.com/{resource_id}/providers/Microsoft.Authorization/permissions?api-version=2022-04-01`** you can get the permissions you have over the specified resource in the **`resource_id`**.

Therefore, **checking each of the resources you have access to**, you can get the permissions you have over them.

> [!WARNING]
> You can automate this enumeration using the tool **[Find_My_Az_Management_Permissions](https://github.com/carlospolop/Find_My_Az_Management_Permissions)**.


<details>
<summary>Enumerate permissions with **`Microsoft.Authorization/roleAssignments/read`**</summary>

> [!TIP]
> Note that you need the permission **`Microsoft.Authorization/roleAssignments/read`** to execute this action.

- With enough permissions, the role **`Get-AzRoleAssignment`** can be used to **enumerate all the roles** in the subscription or the permission over a specific resource indicatig it like in:
```bash
Get-AzRoleAssignment -Scope /subscriptions/<subscription-id>/resourceGroups/Resource_Group_1/providers/Microsoft.RecoveryServices/vaults/vault-m3ww8ut4
```

It's also possible to get this information running:
```bash
az rest --method GET --uri "https://management.azure.com/<Scope>/providers/Microsoft.Authorization/roleAssignments?api-version=2022-04-01" | jq ".value"
```

like in:

```bash
az rest --method GET --uri "https://management.azure.com//subscriptions/<subscription-id>/resourceGroups/Resource_Group_1/providers/Microsoft.KeyVault/vaults/vault-m3ww8ut4/providers/Microsoft.Authorization/roleAssignments?api-version=2022-04-01" | jq ".value"
```

- Another option is to **get the roles attached to you in azure**. This also requires the permission **`Microsoft.Authorization/roleAssignments/read`**:

```bash
az role assignment list --assignee "<email>" --all --output table
```

Or running the following (If the results are empty it might be because you don't have the permission to get them):

```bash
az rest --method GET --uri 'https://management.azure.com/subscriptions/<subscription-id>/providers/Microsoft.Authorization/roleAssignments?api-version=2022-04-01&$filter=principalId eq '<user-id>'
```


- **Find the granular permissions of the roles attached to you**:

Then, to get the granular permission you could run **`(Get-AzRoleDefinition -Id "<RoleDefinitionId>").Actions`**.

Or call the API directly with

```bash
az rest --method GET --uri "https://management.azure.com//subscriptions/<subscription-id>/providers/Microsoft.Authorization/roleDefinitions/<RoleDefinitionId>?api-version=2022-04-01" | jq ".properties"
```

</details>

In the following section you can find **information about the most common Azure services and how to enumerate them**:

{{#ref}}
az-services/
{{#endref}}

### Privilege Escalation, Post-Exploitation & Persistence

Once you know how is the Azure environment structured and what services are being used, you can start looking for ways to **escalate privileges, move laterally, perform other post-exploitation attacks and maintain persistence**.

In the following section you can find information about how to escalate privileges in the most common Azure services:

{{#ref}}
az-privilege-escalation/
{{#endref}}

In the following one you can find information about how to perform post-exploitation attacks in the most common Azure services:

{{#ref}}
az-post-exploitation/
{{#endref}}

In the following one you can find information about how to maintain persistence in the most common Azure services:

{{#ref}}
az-persistence/
{{#endref}}

{{#include ../../banners/hacktricks-training.md}}



