# Azure Pentesting

## Theory

**Azure** is Microsoft's comprehensive cloud computing platform that offers various services including virtual machines, databases, artificial intelligence, storage, and more. It serves as the foundation for hosting applications and managing infrastructure.

**Entra ID** (formerly Azure Active Directory or AAD) is a cloud-based identity and access management service that handles authentication and authorization for Microsoft services like Office 365, Azure, and third-party applications. It provides features such as single sign-on (SSO), multi-factor authentication (MFA), and conditional access policies.

<div align="center"><figure><img src="https://329872044-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FMdUKdzuqIuObdvCB3mUR%2Fuploads%2Fgit-blob-3e0d6a931dc5600e4116f5f597462eda19b152a1%2Fimage.png?alt=media" alt=""><figcaption><p><a href="https://www.synacktiv.com/en/publications/azure-ad-introduction-for-red-teamers.html#azure-ad-overview">https://www.synacktiv.com/en/publications/azure-ad-introduction-for-red-teamers.html#azure-ad-overview</a></p></figcaption></figure></div>

**Entra Domain Services** (formerly Azure AD DS) extends Entra ID by providing managed domain services compatible with traditional Windows Active Directory environments. It supports legacy protocols like LDAP, Kerberos, and NTLM, allowing organizations to run older applications in the cloud without deploying on-premises domain controllers.

### Azure Organization Hierarchy

Understanding the hierarchical structure of Azure resources is critical for identifying potential attack paths:

1. **Management Groups**: Contains other management groups or subscriptions, allowing governance controls such as RBAC and Azure Policy to be applied and inherited by all subscriptions in the group.

   * A single directory can support up to 10,000 management groups
   * Management group trees can be up to 6 levels deep (excluding root level and subscription level)
   * Each management group and subscription can have only one parent
   * All subscriptions within a management group must trust the same Entra ID tenant

   <div align="center"><figure><img src="https://329872044-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FMdUKdzuqIuObdvCB3mUR%2Fuploads%2Fgit-blob-6baae7976bdb373b45584ced2436106bd555bdd3%2Fimage.png?alt=media" alt="" width="563"><figcaption></figcaption></figure></div>
2. **Subscriptions**: Logical containers where resources are deployed and billed.
   * Parent is always a management group
   * Can only trust one Entra ID directory
   * Permissions applied at this level are inherited by all resources inside
3. **Resource Groups**: Containers holding related resources that share the same lifecycle.

   * All resources must be inside a resource group
   * Resources can only belong to one group
   * When a resource group is deleted, all resources inside are also deleted

   <div align="center"><figure><img src="https://329872044-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FMdUKdzuqIuObdvCB3mUR%2Fuploads%2Fgit-blob-5c0e75ab1910146cdf1d4ebbd0968005a1eeccf7%2Fimage.png?alt=media" alt="" width="561"><figcaption></figcaption></figure></div>
4. **Resources**: Individual services (VMs, databases, storage accounts, etc.)

{% hint style="info" %}
**Azure Resource IDs**

Every resource in Azure has a unique Resource ID with the format: `/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}`

Example for a VM named "myVM": `/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myV`
{% endhint %}

### Entra ID Principals and Identity Components

**Identity Principals** in Entra ID (Azure AD) are security entities that can be authenticated and authorized to access resources.

Principals are the cornerstone of Azure's security model as they represent "who" is trying to access "what" resources. Understanding principals is crucial for red teamers and pentesters as they often represent potential entry points, privilege escalation paths, and persistence opportunities.

Every principal in Azure can:

* Be assigned access rights through Azure RBAC roles and Entra ID roles
* Be authenticated through various mechanisms (passwords, certificates, tokens)
* Have their access restricted through Conditional Access Policies
* Leave audit trails in logs when accessing resources

<details>

<summary>Users</summary>

Users are the most basic type of principal, representing human identities in the system.

**Types of Users**

* **Members** – Regular users within the organization (employees, contractors).
* **Guests** – External users invited from other organizations or personal accounts.

Below is a quick overview of defult permissions for members and guest. More details can be found on this link: <https://learn.microsoft.com/en-us/entra/fundamentals/users-default-permissions>

<table><thead><tr><th width="177.4327392578125">Category</th><th width="261.34326171875">Members</th><th>Guests (Default Limited Access)</th></tr></thead><tbody><tr><td><strong>Directory Read</strong></td><td>Can read all users, groups, applications, devices, roles, subscriptions</td><td>Limited to own profile only</td></tr><tr><td><strong>Group Management</strong></td><td>• Create security groups<br>• Read non-hidden group memberships<br>• Add guests to owned groups</td><td>• Cannot create groups<br>• Can only see owned group memberships</td></tr><tr><td><strong>Application</strong></td><td>• Create new applications (configurable)<br>• Read all applications</td><td>Cannot create applications</td></tr><tr><td><strong>Device</strong></td><td>Can add up to 50 devices (configurable)</td><td>Cannot register devices</td></tr><tr><td><strong>Guest Invitation</strong></td><td>Can invite guests (configurable)</td><td>Cannot invite guests by default</td></tr><tr><td><strong>Profile</strong></td><td>Full access to own profile</td><td>Limited access to own profile</td></tr><tr><td><strong>Portal Access</strong></td><td>Access to admin portal (configurable)</td><td>Limited portal access</td></tr><tr><td><strong>Resource Access</strong></td><td>Requires explicit permissions</td><td>Requires explicit permissions</td></tr></tbody></table>

> Note: All these permissions can be further restricted by administrators through organizational settings.

</details>

<details>

<summary>Groups</summary>

Groups are collections of users and other principals. There are **2 types of groups**:

* **Security**: This type of group is used to give members access to aplications, resources and assign licenses. Users, devices, service principals and other groups an be members.
* **Microsoft 365**: This type of group is used for collaboration, giving members access to a shared mailbox, calendar, files, SharePoint site, and so on. Group members can only be users.
  * This will have an **email address** with the domain of the EntraID tenant.

There are **2 types of memberships**:

* **Assigned**: Allow to manually add specific members to a group.
* **Dynamic membership**: Automatically manages membership using rules, updating group inclusion when members attributes change.

</details>

<details>

<summary>Service Principals</summary>

A **Service Principal** is an **identity** designed for applications, hosted services, and automated tools to access Azure resources. It functions similarly to service accounts in traditional Active Directory.

Service Principal access is controlled by the roles assigned to it, determining which resources can be accessed and their access levels.

It's possible to **directly login as a service principal** by generating it a **secret** (password), a **certificate**, or granting **federated** access to third party platforms (e.g. Github Actions) over it.

* If you choose **password** auth (by default), **save the password generated** as you won't be able to access it again.
* If you choose certificate authentication, make sure the **application will have access over the private key**.

</details>

<details>

<summary>App Registrations</summary>

App registrations are the configurations that allow applications to integrate with Entra ID. They are the "blueprint" from which service principals are created.

**Key Components:**

1. **Application ID (Client ID):** A unique identifier for your app in Azure AD.
2. **Redirect URIs:** URLs where Azure AD sends authentication responses.
3. **Certificates, Secrets & Federated Credentials:** It's possible to generate a secret or a certificate to login as the service principal of the application, or to grant federated access to it (e.g. Github Actions).
   1. If a **certificate** or **secret** is generated, it's possible to a person to **login as the service principal** with CLI tools by knowing the **application ID**, the **secret** or **certificate** and the **tenant** (domain or ID).
4. **API Permissions:** Specifies what resources or APIs the app can access.
5. **Authentication Settings:** Defines the app's supported authentication flows (e.g., OAuth2, OpenID Connect).
6. **Service Principal**: A service principal is created when an App is created (if it's done from the web console) or when it's installed in a new tenant.
   1. The **service principal** will get all the requested permissions it was configured with.

</details>

<details>

<summary>Default Consent Permissions</summary>

Consent permissions define how users and administrators approve applications to access organizational data.

Organizations can control whether users can consent to applications requesting permissions to access their data. There are three main settings:

<table data-header-hidden><thead><tr><th width="157.2239990234375"></th><th width="387.044677734375"></th><th></th></tr></thead><tbody><tr><td><strong>Setting</strong></td><td><strong>Description</strong></td><td><strong>Security Level</strong></td></tr><tr><td>Do Not Allow User Consent</td><td>Only administrators can grant consent for applications. This ensures maximum control but increases administrative overhead.</td><td>🔒 High</td></tr><tr><td>Allow User Consent for Verified and Low-Impact Apps (Recommended)</td><td>Users can consent to apps from <strong>verified publishers</strong>, internal applications, and apps requesting <strong>only low-impact permissions</strong>.</td><td>🟠 Medium</td></tr><tr><td>Allow User Consent for All Applications (Default)</td><td>Any user can consent to <strong>any application</strong> requesting access to organizational data. This provides flexibility but increases risk.</td><td>🔴 Low</td></tr></tbody></table>

**Low-Impact Permissions (Must Be Accepted as Low Impact)**

| Permission      | **Purpose**                         |
| --------------- | ----------------------------------- |
| User.Read       | Sign in and read user profile       |
| offline\_access | Maintain access to granted data     |
| openid          | Enable user authentication          |
| profile         | View basic user profile information |
| email           | Access the user's email address     |

**Admin Consent Requests**

| **Setting**                                 | **Description**                                                                                                                                                                                                                                        |
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Default (No Admin Consent Requests Allowed) | Users cannot request administrator approval for apps they are unable to consent to.                                                                                                                                                                    |
| Admin Consent Requests Enabled              | Organizations can allow users to request admin consent for restricted apps. Admins can define **who** can approve requests (specific users, groups, or roles) and configure **email notifications** and **expiration reminders** for pending requests. |

</details>

<details>

<summary>Managed Identities (<strong>Metadata)</strong></summary>

Managed identities are Azure's solution for secure service-to-service authentication without storing credentials. It's a solution for automatically managing the identity of applications.

This allows to **remove the need of hardcoding cloud credentials** in the code as the application will be able to contact the **metadata** service to get a valid token to **perform actions** as the indicated managed identity in Azure.

There are two types of managed identities:

* **System-assigned**. Some Azure services allow you to **enable a managed identity directly on a service instance**. When you enable a system-assigned managed identity, a **service principal** is created in the Entra ID tenant trusted by the subscription where the resource is located. When the **resource** is **deleted**, Azure automatically **deletes** the **identity** for you.
* **User-assigned**. It's also possible for users to generate managed identities. These are created inside a resource group inside a subscription and a service principal will be created in the EntraID trusted by the subscription. Then, you can assign the managed identity to one or **more instances** of an Azure service (multiple resources). For user-assigned managed identities, the **identity is managed separately from the resources that use it**.

</details>

<details>

<summary>Enterprise Applications</summary>

It’s just a **table in Azure to filter service principals** and check the applications that have been assigned to.

**It isn’t another type of “application”,** there isn’t any object in Azure that is an “Enterprise Application”, it’s just an abstraction to check the Service principals, App registrations and managed identities.

</details>

<details>

<summary>Administrative Units</summary>

Administrative Units (AUs) enable organizations to delegate **role-based permissions** over a specific subset of users, groups, or devices within an organization. This allows for **granular administrative control** without granting broad tenant-wide permissions.

</details>

<details>

<summary>Entra ID Roles &#x26; Permissions</summary>

Entra ID provides built-in roles that can be assigned to Entra ID principals to manage various identity-related functionalities.

* **Privileged Roles:** Some roles are marked as **`PRIVILEGED`**, meaning they can lead to elevation of privileges if not properly secured. The most privileged role is **Global Administrator**.
* **Granular Permissions:** Roles group specific permissions, which are listed in their descriptions.
* **Custom Roles:** Administrators can create custom roles with specific permissions, although not all granular permissions are available.
* **Independence from Azure Roles:** Entra ID roles are entirely separate from Azure roles. However, a **Global Administrator** in Entra ID can elevate to **User Access Administrator** in Azure.
* **Wildcard Usage:** Wildcards cannot be used in Entra ID roles.

[Refer to the official documentation](https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference) for a full list of roles.

</details>

### Azure Roles & Permissions

#### Role Assignment Model

* Roles are assigned following the pattern: `principal -[HAS ROLE]->(scope)`
* Principals can be users, groups, service principals, or managed identities
* Group role assignments are inherited by all group members

#### Inheritance Structure

* Roles inherit downward through the Azure hierarchy:
* Management Groups → Subscriptions → Resource Groups → Resources
* Example: A role assigned at subscription level applies to all contained resource groups and resources

#### Types of Roles

<details>

<summary>Built-In Roles</summary>

[Azure role-based access control (Azure RBAC)](https://learn.microsoft.com/en-us/azure/role-based-access-control/overview) has several Azure [built-in roles](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles) that you can assign to users, groups, service principals, and managed identities.

</details>

<details>

<summary>Custom Roles</summary>

Organizations can define [custom roles](https://learn.microsoft.com/en-us/azure/role-based-access-control/custom-roles) in and Azure. Custom roles are created within a **scope**, such as management groups, subscriptions, or resource groups. They can include or exclude specific permissions. Azure roles support wildcards (`*`) for broad permission assignments. Permissions are categorized into :

* **actions:** Manage resources (e.g., create, update, delete configurations).
* **dataActions:** Control access to actual resource data.
* **notActions / notDataActions:** Explicitly exclude specific permissions.
* **assignableScopes:** Defines where the role can be applied.

{% code title="Example Custom Role JSON" %}

```json
{
  "properties": {
    "roleName": "",
    "description": "",
    "assignableScopes": ["/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f"],
    "permissions": [
      {
        "actions": [
          "Microsoft.DigitalTwins/register/action",
          "Microsoft.DigitalTwins/unregister/action",
          "Microsoft.DigitalTwins/operations/read",
          "Microsoft.DigitalTwins/digitalTwinsInstances/read",
          "Microsoft.DigitalTwins/digitalTwinsInstances/write",
          "Microsoft.CostManagement/exports/*"
        ],
        "notActions": [
          "Astronomer.Astro/register/action",
          "Astronomer.Astro/unregister/action",
          "Astronomer.Astro/operations/read",
          "Astronomer.Astro/organizations/read"
        ],
        "dataActions": [],
        "notDataActions": []
      }
    ]
  }
}
```

{% endcode %}

</details>

#### Permissions Order

Access to a resource requires an explicit **role assignment**. **Deny assignments take precedence** over role assignments, preventing access even if a role grants permission.

<figure><img src="https://329872044-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FMdUKdzuqIuObdvCB3mUR%2Fuploads%2Fgit-blob-e142af0166a6e9130862a8ae49fbb4dd5fdebad8%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

#### Deny Assignments <a href="#deny-assignments" id="deny-assignments"></a>

Just like role assignments, **deny assignments** are used to **control access to Azure resources**. However, **deny assignments** are used to **explicitly deny access** to a resource, even if a user has been granted access through a role assignment. **Deny assignments** take precedence over **role assignments**, meaning that if a user is granted access through a role assignment but is also explicitly denied access through a deny assignment, the deny assignment will take precedence.

Just like role assignments, **deny assignments** are applied over some scope indicating the affected principals and the permissions that are being denied. Moreover, in the case of deny assignments, it's possible to **prevent the deny to be inherited** by children resources.

#### Global Administrator

This role grants complete control over the Entra ID tenant but does not provide default permissions over Azure resources. A Global Administrator can elevate to **User Access Administrator** in the Azure **Root Management Group**, allowing them to manage access across all Azure subscriptions. Elevation can be performed [here](https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/Properties).

<figure><img src="https://329872044-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FMdUKdzuqIuObdvCB3mUR%2Fuploads%2Fgit-blob-cb0ae6902a5e70942081e6bfac98c5f4761f25d7%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

#### Azure Policies <a href="#azure-policies" id="azure-policies"></a>

**Azure Policies** are rules that help organizations ensure their resources meet specific standards and compliance requirements. They allow you to **enforce or audit settings on resources in Azure**. For example, you can prevent the creation of virtual machines in an unauthorized region or ensure that all resources have specific tags for tracking.

Azure Policies are **proactive**: they can stop non-compliant resources from being created or changed. They are also **reactive**, allowing you to find and fix existing non-compliant resources.

A **Policy Definition** specifies compliance requirements in JSON format. Policies are applied at a **scope**, such as a subscription or resource group.

* **Initiatives** group multiple policies for broader enforcement.
* **Effects** define policy actions, such as **Deny**, **Audit**, or **Append**.

{% code title="Azure policy json example" %}

```json
{
  "policyRule": {
    "if": {
      "field": "location",
      "notIn": ["eastus", "westus"]
    },
    "then": {
      "effect": "Deny"
    }
  },
  "parameters": {},
  "displayName": "Allow resources only in East US and West US",
  "description": "This policy ensures that resources can only be created in East US or West US.",
  "mode": "All"
}

```

{% endcode %}

#### Permissions Inheritance <a href="#permissions-inheritance" id="permissions-inheritance"></a>

In Azure **permissions are can be assigned to any part of the hierarchy**. That includes management groups, subscriptions, resource groups, and individual resources. Permissions are **inherited** by contained **resources** of the entity where they were assigned.

This hierarchical structure allows for efficient and scalable management of access permissions.

<figure><img src="https://329872044-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FMdUKdzuqIuObdvCB3mUR%2Fuploads%2Fgit-blob-51907ad6f092f41f98444e662887c52205f8d553%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

#### Azure RBAC vs ABAC <a href="#azure-rbac-vs-abac" id="azure-rbac-vs-abac"></a>

**RBAC** (role-based access control) is what we have seen already in the previous sections: **Assigning a role to a principal to grant him access** over a resource.\
However, in some cases you might want to provide **more fined-grained access management** or **simplify** the management of **hundreds** of role **assignments**.

Azure **ABAC** (attribute-based access control) builds on Azure RBAC by adding **role assignment conditions based on attributes** in the context of specific actions. A *role assignment condition* is an **additional check that you can optionally add to your role assignment** to provide more fine-grained access control. A condition filters down permissions granted as a part of the role definition and role assignment. For example, you can **add a condition that requires an object to have a specific tag to read the object**.\
You **cannot** explicitly **deny** **access** to specific resources **using conditions**.

## Resources

{% embed url="<https://cloud.hacktricks.wiki/en/pentesting-cloud/azure-security/az-basic-information/index.html>" %}

{% embed url="<https://www.synacktiv.com/en/publications/azure-ad-introduction-for-red-teamers.html#azure-ad-overview>" %}
