Penetration Testing Azure for Ethical Hackers

By David Okeyode , Karl Fosaaen
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Chapter 1: Azure Platform and Architecture Overview

About this book

Security professionals working with Azure will be able to put their knowledge to work with this practical guide to penetration testing. The book provides a hands-on approach to exploring Azure penetration testing methodologies that will help you get up and running in no time with the help of a variety of real-world examples, scripts, and ready-to-use source code.

As you learn about the Microsoft Azure platform and understand how hackers can attack resources hosted in the Azure cloud, you'll find out how to protect your environment by identifying vulnerabilities, along with extending your pentesting tools and capabilities. This book starts by taking you through the prerequisites for pentesting Azure and shows you how to set up a pentesting lab. You'll then simulate attacks on Azure assets such as web applications and virtual machines from anonymous and authenticated perspectives. Finally, you'll learn about the opportunities for privilege escalation in Azure tenants and ways in which an attacker can create persistent access to an environment.

By the end of this book, you'll be able to leverage your ethical hacking skills to identify and implement different tools and techniques to perform successful penetration tests on your own Azure infrastructure.

Publication date:
November 2021
Publisher
Packt
Pages
352
ISBN
9781839212932

 

Chapter 1: Azure Platform and Architecture Overview

The Azure cloud is Microsoft's public cloud computing platform. The platform consists of multiple services that customers can use to develop, host, and enhance their applications and services. Like many other cloud platforms (Amazon Web Services (AWS), Google Cloud Platform (GCP), and so on), it is constantly growing and evolving by frequently adding new services and features to the ecosystem. Given the availability of all of these cloud services, and the flexibility of Microsoft 365 licensing, many organizations are moving their operations up into the Azure cloud.

In our first chapter, we will focus on providing an overview of the Azure platform, its architecture, the core services, and how those services are managed.

In this chapter, we'll cover the following topics:

  • The basics of Microsoft's Azure infrastructure
  • An overview of Azure services
  • Understanding the Azure role-based access control (RBAC) structure
  • Accessing the Azure cloud

By the end of the chapter, we will have a good understanding of how organizations use Azure and how to approach an Azure environment as a penetration tester.

 

Technical requirements

You won't need any additional software for most of this first chapter, as we will be focusing on attaining a high-level understanding of the Azure infrastructure. Having Azure portal access to an existing subscription is certainly handy for following along, but not needed for understanding the concepts.

At the end of the chapter, we will review the multiple methods for accessing the Azure management interfaces. So, if you do have access to an existing Azure environment, the following tools will be helpful to have available:

  • The Azure command-line interface (CLI)
  • The Az PowerShell module
  • The Azure Active Directory (Azure AD) PowerShell module

If you don't have access to an existing Azure environment, don't worry. We will go through the steps to creating your own testing environment in Chapter 2, Building Your Own Environment.

 

The basics of Microsoft's Azure infrastructure

At the time of writing (late 2020–early 2021), the Azure platform consists of over 200 services and seems to be expanding all the time. It may feel that there is a lot of ground to cover here, but during a penetration test, you will typically only need to focus on a subset of the available services that you have in scope.

In general, it is important to understand how the environment is structured at the Azure platform level (subscriptions, RBAC, resources), and how the available services can be abused to gain additional privileges in the environment.

The lessons in this section will be fundamental to your understanding of how Azure functions as a platform, so pay close attention. For those with a solid Azure background, feel free to skim this chapter to refresh on the core principles.

In this section, we will gain an understanding of the Azure cloud platform and its regions, how Azure tenants are typically structured, and how the resources under the tenant are managed.

Azure clouds and regions

To be able to serve several distinct markets governed by different laws and regulations, Microsoft has built different Azure clouds that cater to different markets. These clouds all run on the same technologies and provide the same services, but they run in different data center environments that are isolated both physically and logically. This is important to keep in mind, as the application programming interface (API) endpoints for each platform and their services vary depending on the cloud platform that we are interacting with.

The following table highlights the four Azure cloud platforms and their main endpoints:

Since each of these clouds has different endpoints for accessing Azure services and we want to avoid confusion across regions, we will standardize on the Azure Commercial cloud for all the examples in the book. It is important to note that the examples are applicable to the other Azure clouds, but you may need to modify the target endpoints.

Azure resource management hierarchy

Before we get into the tactics, techniques, and procedures that can be used during penetration tests in Azure environments, we need a working understanding of how resources are structured in the Azure cloud. This knowledge will also give us the ability to follow an attack chain through an environment once we have obtained initial access.

The organization structure in Azure consists of the following levels: Azure AD Tenant, Root Management Group, Child Management Group, Subscription, Resource Group, and individual Resources. These different levels are shown in the following diagram:

Figure 1.1 – Azure resource hierarchy

Figure 1.1 – Azure resource hierarchy

Here are the descriptions of each level from the top down:

  • Azure AD Tenant: In order to manage Azure subscriptions and resources, administrators need an identity directory to manage users that will have access to the resources. Azure AD is the identity store that facilitates the authentication and authorization for all users in an Azure tenant's subscriptions.

    Every Azure subscription has a trust relationship with one Azure AD tenant to manage access to the subscription. It is common for organizations to connect their on-premises AD to Azure AD using a tool called Azure AD Connect, as shown in the following diagram:

Figure 1.2 – Using Azure AD Connect to synchronize objects to Azure AD

Figure 1.2 – Using Azure AD Connect to synchronize objects to Azure AD

As the core of authentication and authorization, Azure AD is a prime target for information gathering, as well as different identity-based attacks. We will be covering more of the authorization model for Azure subscriptions in the Understanding the Azure RBAC structure section in this chapter.

  • Root Management Group: This is the top of the Azure resource organization hierarchy, if it's enabled. By default, the root management group is not enabled for an organization that is new to Azure, which means each subscription is managed as an individual entity. However, managing subscriptions individually creates a governance model that does not scale well. This is especially difficult for medium- to large-sized organizations with multiple subscriptions to manage.

    Many production Azure environments will have the root management group enabled. This is partly because Microsoft recommends enabling it as part of their Cloud Adoption Framework document (https://docs.microsoft.com/en-us/azure/cloud-adoption-framework/decision-guides/subscriptions/). This document describes some of the best practices for adopting the Azure cloud and is a great source of information for those looking at building out an environment in Azure.

  • Child Management Group: If an organization has enabled the root management group, they could create child management groups under the root to simplify the management of their subscriptions. Child management groups allow organizations to group subscriptions together in a flexible structure, mainly to centrally manage access and governance. Child management groups can be nested and can support up to six levels of depth.
  • Subscription: To provision resources in Azure, we need an Azure subscription. An Azure subscription is the logical container where resources are provisioned. When we create a resource such as a Structured Query Language (SQL) database, the first thing we usually do is specify the subscription where the resource will be provisioned. The usage of that resource will also be billed to the subscription that is selected.

    As noted in the Child Management Group description, an organization will typically have multiple Azure subscriptions. It is quite common for organizations to set up multiple subscriptions for separate environments, such as development and production, or for separating application environments.

  • Resource Group: Within subscriptions, there are resource groups. Resource groups are logical containers that can be used to group and manage Azure resources such as virtual machines (VMs), storage accounts, and databases.

    Resource groups are best used to collect and group resources that need to be managed together or share the same life cycle. Depending on the subscription architecture, this can result in large numbers of resource groups in individual subscriptions.

    From an access perspective, resource groups also allow us to segment access to different groups in the same subscription, but we will cover that in more detail in the Understanding the Azure RBAC structure section.

  • Resources: Resources are the individual instances of Azure services that are deployed in an Azure subscription. The resource level is the bottom of the organization hierarchy. Outside of services with specific access policies (see the information about key vaults), we can't segment down the resources hierarchy any further than this.

We will get into the specifics of how access is managed using RBAC later in the chapter but in general, an Azure AD account can have specified access to any of the resource organization levels outlined previously. From a penetration-testing perspective, access granted at a higher level gives wider scope for an attacker to discover vulnerabilities in cloud-service configurations and to move laterally within the environment. This concept will be more important when we discuss privilege escalation.

In the next section, we will cover an overview of some of the commonly utilized Azure services. These individual instances of services fall under the Resources category listed previously.

 

An overview of Azure services

As we noted earlier in this chapter, there are over 200 services available in Azure. Even though this sounds like a lot of services, they can generally be grouped into five categories, outlined as follows:

  • Services that are used to host applications: These services provide a runtime environment that can be used to execute application code or run container images. Services such as Azure App Service, Azure Virtual Machine (Azure VM), and Azure Kubernetes Service (AKS) fall into this category. Organizations use them to host external and internal applications.
  • Services that are used to store data for applications: These services are used to store different kinds of application data. Services such as Storage accounts, Azure SQL, and Cosmos DB fall into this category.
  • Services that are used to create applications: These services are used to create workflows that run in the cloud. Services such as Logic Apps and Functions apps fall into this category.
  • Services that are used to enhance applications: These are typically Software-as-a-Service (SaaS)-type services in Azure that are used to provide extra capabilities to other applications. A service such as Azure Cognitive Services falls into this category. This is used by developers to add intelligence to their custom applications using pre-built and pre-trained machine learning algorithms.
  • Services that are used to monitor or manage applications: These are services that are used to manage or monitor other services or applications. Services such as Azure Automation, API Management, Application Insights, and Azure Monitor fall into this category. Additional security-focused services, such as Azure Sentinel and Azure Security Center, would also fall into this category. These services can also provide useful insights from a penetration-testing perspective.

As we progress through the book, we will touch on many services, but the core resources that are important to understand are outlined here.

This table outlines some of the most common Azure services that will be attacked in this book:

As you can see from the preceding information, Microsoft was very practical with the naming of Azure services. For the most part, the service names are based on what the service does. For example, the Azure service used for hosting VMs is called Virtual Machines. In contrast, the equivalent service in AWS would be Elastic Compute Cloud (EC2).

Important note

For anyone that is making the terminology transition from AWS to Azure, the following Microsoft document may be helpful for matching up any of the confusing service names: https://docs.microsoft.com/en-us/azure/architecture/aws-professional/services.

For those more familiar with GCP, Microsoft also has some helpful documentation at https://docs.microsoft.com/en-us/azure/architecture/gcp-professional/services.

In Chapter 3, Finding Azure Services and Vulnerabilities, we will discuss how some of these services can be discovered anonymously using the Azure Domain Name System (DNS) naming structure. In the next section, we will review how access to Azure services is structured and managed using RBAC.

 

Understanding the Azure RBAC structure

RBAC is an authorization system used to control who has access to Azure resources, and the actions users can take against those resources. At a high level, you can think of it as granting security principals (users, groups, and applications) access to Azure resources, by assigning roles to the security principals.

For example, RBAC can be used to grant a user access to manage all VMs in a subscription, while another user is granted access to manage all storage accounts in the same subscription. That would be an odd choice for separation of duties in a subscription, but cloud environments tend to foster creative solutions for making things work.

RBAC concepts get far more complex when we start introducing the different scopes of role assignments (management groups, subscriptions, and so on), but keep the preceding description in mind as we progress.

Azure RBAC is made up of the following components—security principals, role definitions, and role assignment. Let's look at each of these components in detail.

Security principals

A security principal is a fancy term to describe an Azure AD object that we want to assign privileges to. This could be a user account, a group, a service principal, or a managed identity. These are all different types of identities that exist in Azure AD, as shown in the following screenshot:

Figure 1.3 – Azure RBAC security principals

Figure 1.3 – Azure RBAC security principals

Important note

Do not confuse ''security principal'' with ''service principal." Security principal is an overall term used to describe objects in Azure AD (including users, groups, and service principals). Service principal is a specific type of security principal.

While there are many facets to a security principal, keep in mind that every security principal has an object ID that uniquely identifies it in Azure AD. This object ID is typically used as a reference when assigning a role to the security principal. Next, we will cover the different types of security principals.

User accounts

A user account is a standard user identity in Azure AD. These accounts can be internal to the Azure AD tenant, or an external ''guest'' account. In either case, the general administration of the users will occur at the Azure AD tenant level.

Internal user accounts are user identities created in the Azure AD tenant by an administrator. Additionally, these may be user identities that are synchronized from an on-premises AD environment to Azure AD (see Figure 1.2).

The accounts are commonly addressed by their User Principal Name (UPN), which is typically an email address. For example, a user named karl in the Azure AD tenant, with a domain name of azurepentesting.com, will have a UPN of [email protected].

The following screenshot shows an internal user account in the Azure portal. Most Azure AD accounts that you interact with will fall under this category:

Figure 1.4 – Screenshot of an internal user account

Figure 1.4 – Screenshot of an internal user account

External user accounts are user identities from other Azure AD tenants, or Microsoft accounts (outlook.com, hotmail.com, and so on) that are invited as guest users to an Azure AD tenant. The UPN format for external user accounts is shown here:

<alias>_<HomeTenant>#EXT#@domain.suffix

For example, if a user named david, from the cloudsecnews.com AD tenant, is invited as a guest user of the globaladministratorazurepen.onmicrosoft.com Azure AD tenant, the UPN will be david_cloudsecnews.com#EXT#@ globaladministratorazurepen.onmicrosoft.com (see Figure 1.5).

External accounts are typically used to grant access to vendors or third-party users that may be working on a subscription. The user accounts are not directly managed by the Azure AD tenant, so account policies (password length, multi-factor authentication (MFA), and so on) would be out of the control of the Azure AD tenant.

Here is a screenshot of an external user account:

Figure 1.5 – Screenshot of an external user account

Figure 1.5 – Screenshot of an external user account

For both internal and external accounts, we will be targeting credentials for the accounts during an Azure penetration test to get access to resources in the Azure AD tenant. As we will see in later chapters, these accounts are a great place to get an initial foothold in an environment.

Service principal

A service principal is an application identity in Azure AD. You can think of it as an Azure AD object representing an application that needs access to Azure resources. This is the preferred way to grant access to an application instead of creating a dummy user account.

Service principals will be very important when we get to automation account attacks, but for now, just know that applications can be registered in Azure AD and they can also be granted permissions in the tenant. For example, you may have an automation account that runs maintenance scripts in a subscription, so you will want to have specific rights granted to the account that runs the scripts. These rights would be applied to the service principal that is created in the Azure AD tenant when the automation account is created.

Service principals can also be assigned certificates and secrets that can be used for authentication. These credentials will be important to note when we want to use the app registrations for privilege escalation, and/or persistence in the Azure AD tenant. The process of creating a service principal is called an app registration.

In the following screenshot, we can see some basic information about an app registration in our sample tenant. As an attacker, we may have situations where it makes sense to create a new service principal that would allow us to persist in an environment. If we choose a generic display name (Backup Service) for creating a backdoor service principal, we may have a better chance of going undetected for longer in the tenant:

Figure 1.6 – Screenshot of a service principal in Azure AD

Figure 1.6 – Screenshot of a service principal in Azure AD

Finally, service principals can have owners set within Azure AD. The owners of the service principals can control the credentials associated with the accounts, so the owners are useful targets for escalation in an environment where service principals have elevated privileges.

Managed identity

There are times that Azure services (VMs, AKS, applications, and so on) may need access to other Azure resources. The easiest way to grant this access is to enable a managed identity for the Azure service. A managed identity is an automatically created and managed service principal that is assigned to a supported Azure service. At the time of writing, there are 27 services that support managed identities in Azure.

Important note

If you're interested in learning more about all of the services that support managed identities in Azure, Microsoft has them documented here: https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/services-support-managed-identities.

A managed identity can either be system-assigned or user-assigned. A system-assigned identity is tied directly to the resource that the identity is created for. A user-assigned identity is first created in a subscription, and then applied to resources. A user-managed identity can be shared by many services, while a system-assigned identity cannot.

In later chapters, we will see that these identities can be used to escalate privileges in a tenant. The important thing to note for now is that anyone who has modification rights on a resource with an assigned managed identity can potentially assume the rights of that managed identity. This is service-dependent, but there are several services (that we will review later) that can readily be used to generate tokens for managed identities.

Groups

Groups are used in Azure AD to organize users and to make it easier to manage access to Azure resources. For example, it is more effective to assign permissions to 200 users in a group than to 200 individual users. Once Azure resource access is granted to a group, future access can then be granted—or revoked—through group memberships.

Similar to user accounts, groups can either be created by administrators in Azure AD or synchronized from an on-premises AD environment. There is also a third scenario, whereby users can be allowed to create their own groups, or join existing public groups, but those groups are typically associated with Microsoft 365 services.

Much as with app registrations, groups can have owners (either user accounts or service principals), and the owners do not have to be a member of the group. Group owners can manage the group and its membership.

Azure AD supports two main types of groups: security groups that are primarily used to manage access to shared resources, and Microsoft 365 groups that serve a similar function to email distribution groups that you may be familiar with in AD. These can also be used to assign access to Azure resources.

Membership of an Azure AD group can either be assigned or dynamic. Assigned memberships are direct user assignments by an administrator or group owner. Dynamic group memberships use rules that are automatically evaluated to determine group membership based on user or device attributes. The rules for dynamic group membership can allow for soft matching, which could be abused to escalate privileges. See the Dynamic group membership section in Chapter 4, Exploiting Reader Permissions, for more information on this attack.

In Azure environments that sync with on-premises AD domains, the complexity of organizing users can increase exponentially as there can be a large number of groups that are imported from the on-premises domain. While there may be a limited number of groups that are actually utilized in the Azure tenant, you may need to deal with hundreds (or thousands) of groups that are in an Azure AD tenant. This shouldn't cause any issues while assessing the Azure environment, but it may complicate things as you begin to pivot to on-premises environments. We will cover tools that help simplify assessing AD groups in Chapter 7, Exploiting Owner and Privileged Azure AD Role Permissions.

Role definition

After security principals, the second component of Azure RBAC is a role definition. This term describes a collection of permissions. A permission describes an action that may or may not be performed on a resource, such as read, write, and delete. We can examine the permissions under a default Azure role to see what it allows us to do.

Here are the permissions for the Contributor role in Azure:

 {
  "assignableScopes": [
    "/"
  ],
  "description": "Grants full access to manage all resources, but does not allow you to assign roles in Azure RBAC, manage assignments in Azure Blueprints, or share image galleries.",
  "id": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c",
  "name": "b24988ac-6180-42a0-ab88-20f7382dd24c",
  "permissions": [
    {
      "actions": [
        "*"
      ],
      "notActions": [
        "Microsoft.Authorization/*/Delete",
        "Microsoft.Authorization/*/Write",
        "Microsoft.Authorization/elevateAccess/Action",
        "Microsoft.Blueprint/blueprintAssignments/write",
        "Microsoft.Blueprint/blueprintAssignments/delete",
        "Microsoft.Compute/galleries/share/action"
      ],
      "dataActions": [],
      "notDataActions": []
    }
  ],
  "roleName": "Contributor",
  "roleType": "BuiltInRole",
  "type": "Microsoft.Authorization/roleDefinitions"
}

We can see in the preceding permissions that a role definition supports two types of operations, as follows:

  • Control-plane operations that describe the management actions that the role can perform. These are defined in the ''actions'': [ ] section. An example of a management action is the permission to create a storage account.
  • Data-plane operations describe the data actions (within a resource) that the role can perform. These are defined in the ''dataActions'': [ ] section. An example of a data action is the permission to read the data that is stored in a storage account.

We can also see in the preceding permissions that certain operations can be excluded for a role. The ''notActions'': [ ] section defines management actions that a role is restricted from performing. The ''notDataActions'': [ ] section defines data actions that a role is restricted from performing.

In the preceding example for the Contributor role, the role has the permission to perform all management (*) actions, but it is restricted (by the notActions definition) from performing authorization-related management actions, which means that the role cannot be used to assign permissions to others. Also, the role does not have the permissions to perform any data action.

It should also be noted that this role definition also contains the ''assignableScopes '': [ ''/'' ] section, which denotes how the role can be applied in the tenant. / indicates that it can be applied at the root of the management group structure, but it can also be applied to any scopes (child management g, subscriptions, and so on) under the root.

Default RBAC roles

At the most basic level, there are three primary roles that are commonly applied in Azure: Reader, Contributor, and Owner. Beyond these three primitive roles, you will find service-specific roles that act as restricted versions of these base roles. These restricted roles are useful for reducing a user's permissions in a specific subscription, but they can still allow for privilege escalation in the environment.

For example, the Virtual Machine Contributor role (applied at the subscription level) does not allow an Azure AD user to be a contributor for all of the services in the subscription. However, the role does allow Microsoft.Compute/virtualMachines/* actions, which means it would allow the user to run commands on any of the VMs in the subscription.

If this VM is configured with a privileged managed identity, that VM Contributor user could run commands on the VM to assume the rights of the managed identity and escalate their privileges. We will dive deeper into this concept in Chapter 5, Exploiting Contributor Permissions on IaaS Services, where we learn about using contributor rights on VMs.

An important point to note is that Azure resources and the Azure AD tenant have separate permission systems. This means that the roles used to grant access to Azure AD are different from the roles used to grant access to Azure resources, as depicted in the following screenshot:

Figure 1.7 – Azure AD roles versus Azure RBAC roles

Figure 1.7 – Azure AD roles versus Azure RBAC roles

Azure AD roles are used to manage access to Azure AD resources and operations, such as user accounts and password resets, while Azure RBAC roles are used to manage access to Azure resources such as storage accounts, SQL databases, and so on.

Both Azure AD and Azure resources have multiple built-in roles with predefined permissions that organizations may use to grant access to users and applications. Both support custom roles that are created by administrators. At the time of writing, there are currently 60 built-in Azure AD roles and over 220 Azure RBAC built-in roles.

Important note

Microsoft has the best documentation on these roles and has a comprehensive list of the available Azure AD roles (https://docs.microsoft.com/en-us/azure/active-directory/roles/permissions-reference) and Azure RBAC roles (https://docs.microsoft.com/en-us/azure/role-based-access-control/built-in-roles).

Role assignment

Next, we need to understand how the roles are applied in an Azure AD tenant. Returning to Figure 1.1, we noted the Azure resource organization hierarchy. One of the interesting design choices in the Azure cloud is the way that RBAC roles are applied to this hierarchy. As noted previously, RBAC roles can be applied at the root management group, child management group, subscription, resource group, and individual resource levels.

Any role-based access that is assigned at the root management group level propagates throughout the organization and cannot be overridden at a lower level. If an attacker manages to steal a credential that gives access at the root management group level, they could leverage this access to move laterally across different subscriptions in the organization.

Now that we have a better understanding of the RBAC structure, let's take a look at how we can interact with the Azure environment.

 

Accessing the Azure cloud

There are multiple ways to interact with an Azure tenant, and each method has specific advantages during a penetration test. The following list outlines the ways the Azure cloud can be accessed:

  • Azure portal
  • Azure CLI
  • Az PowerShell cmdlets
  • Azure REST APIs

In Chapter 2, Building Your Own Environment, we will discuss setting up your own environment, but if you already have access to an Azure environment, feel free to follow along with these access methods.

Azure portal

The Azure portal is a web-based console for accessing and managing Azure resources. The URL for the Azure public cloud platform is https://portal.azure.com. As noted at the start of the chapter, the address is different for other Azure clouds, such as those for the US government, China, and Germany.

A user has to first authenticate using an Azure AD user account to gain access to the portal. For those of you that are visual learners, the Azure portal will be the best starting point for understanding the resources in an Azure tenant.

Within the portal, there are blades on the left-hand side of the site for each Azure service, as illustrated in the following screenshot:

Figure 1.8 – Azure portal navigation

Figure 1.8 – Azure portal navigation

If the service you are looking for is not in one of the blades, you can use the search bar at the top of the site to find the service you're looking for, as illustrated in the following screenshot:

Figure 1.9 – Azure service search

Figure 1.9 – Azure service search

There are a few specific blades/services that we will focus on later in the book, but for now, it will be important to become familiar with navigating through services and the subscriptions/tenants that are available for your user.

In the top-right corner of the portal, you can select your signed-in user and select Switch directory to see all of the available Azure AD directories for your user, as illustrated in the following screenshot:

Figure 1.10 – Azure user menu

Figure 1.10 – Azure user menu

Depending on the tenants that your account has access to, you may see more than one directory here. These are the different Azure AD tenants that you have (direct membership or guest) access to. Once a directory is selected, you can navigate to the Subscriptions blade to see the subscriptions that you have access to, as illustrated in the following screenshot:

Figure 1.11 – Azure subscriptions list

Figure 1.11 – Azure subscriptions list

In the Subscriptions section, take note of the My role column, as this will let you know your current user's RBAC role in the subscription. Within the individual subscriptions, you can also use the IAM blade to see the rights of other users in the subscription.

Cloud Shell

Within the portal, there is a small PowerShell prompt >_ icon available to the right of the search bar. This icon activates the Azure Cloud Shell within the portal. This can also be accessed via https://shell.azure.com and is shown in the following screenshot:

Figure 1.12 – Azure Cloud Shell portal link

Figure 1.12 – Azure Cloud Shell portal link

If a Cloud Shell has not already been set up for your account, this will require you to select a storage account to use for Cloud Shell storage. Once in the Cloud Shell, your prompt should look like this:

Figure 1.13 – Azure Cloud Shell

Figure 1.13 – Azure Cloud Shell

When setting up your Cloud Shell, you can choose a Bash or PowerShell environment. Both environments have their benefits and they both have the Az CLI ready to use in the shell.

While the Azure Cloud Shell is preloaded with all of tools you need to manage an Azure environment, it also comes with some risks. We will see in later chapters how this service can be used for privilege escalation attacks.

Azure CLI

Another popular option for managing Azure environments is the Azure CLI. Installation of the CLI is simple for Windows systems. Keep in mind that we will be installing the CLI as part of the next chapter's exercises, but if you want to install the CLI on another system, you can download the Microsoft installer for the latest version here: https://aka.ms/installazurecliwindows.

Important note

Since the preceding link is for an executable, it's understandable if you're not immediately rushing to open it. As a general note, we will be using more of these links throughout the book to connect you with Microsoft resources.

The aka.ms links in the book should be safe to follow, as they are all managed by Microsoft's internal short-link service.

For those looking for more information on the CLI, along with options for installing on other operating systems, here is Microsoft's Azure CLI documentation page: https://docs.microsoft.com/en-us/cli/azure/install-azure-cli.

Once installed, open a PowerShell session (powershell.exe) and run the following command:

PS C:\> az login
The default web browser has been opened at https://login.microsoftonline.com/common/oauth2/authorize. Please continue the login in the web browser. If no web browser is available or if the web browser fails to open, use device code flow with `az login --use-device-code`.
You have logged in. Now let us find all the subscriptions to which you have access...
[  {
    ''cloudName'': ''AzureCloud'',
    ''homeTenantId'': ''40d5707e-b434-XXXX-YYYY-ZZZZZZZZZZZZ'',
    ''id'': ''204cce89-27de-4669-a48b-04c27255e05e'',
    ''isDefault'': true,
    ''managedByTenants'': [],
    ''name'': ''Development'',
    ''state'': ''Enabled'',
    ''tenantId'': ''40d5707e-b434-XXXX-YYYY-ZZZZZZZZZZZZ'',
    ''user'': {
      ''name'': ''[email protected]'',
      ''type'': ''user''
    }
  }
]
PS C:\>

This will open a browser window to prompt you to authenticate to Azure. If you are already portal-authenticated in the browser, your username should be populated in the login screen. Log in with your account, and the CLI should be authenticated. This process will also list out all of your available subscriptions.

For starters, use the az command to list out the available options, as follows:

PS C:\ > az
     /\
    /  \    _____   _ _  ___ _
   / /\ \  |_  / | | | \'__/ _\
  / ____ \  / /| |_| | | |  __/
 /_/    \_\/___|\__,_|_|  \___|
Welcome to the cool new Azure CLI!
Use `az --version` to display the current version.
Here are the base commands:
    account : Manage Azure subscription information.
    acr : Manage private registries with Azure Container Registries.
    ad : Manage Azure Active Directory Graph entities needed for Role Based Access Control.
    advisor : Manage Azure Advisor.
     [Truncated]

Typically, the commands that you will run in the CLI will be related to the service name (acr, appservice, vm), and then an action that you want to take.

For example, here's how you would list out resources in your default subscription:

PS C:\ > az resource list

If you need ideas for options on the commands that you might be able to run, use the --help flag to list out your available options.

This is a powerful tool to use for managing Azure, and we will be using it for a few of the book examples in future chapters. That being said, most of our examples will be focused on the Azure PowerShell modules and on tools that utilize them. Before we dive into the specific modules, we want to make sure that we have a basic understanding of Microsoft's PowerShell programming language.

PowerShell

For subscriptions large and small, it is convenient to have access to the flexibility of PowerShell for parsing data. Azure subscriptions can contain large numbers of resources, and those can be quite difficult to parse by hand in the portal.

Here are some quick notes for those that are not as familiar with PowerShell:

  • PowerShell is a command shell, like cmd.exe.
  • When you are running PowerShell or the PowerShell Integrated Scripting Environment (ISE), we will refer to that as a session.
  • PowerShell is also a scripting language that has deep ties with the .NET runtimes and Windows APIs.
  • PowerShell modules are sets of functions that can be imported into a PowerShell session.
  • PowerShell modules can be imported directly from files or installed from external sources, such as the PowerShell Gallery (PSGalleryhttps://www.powershellgallery.com/). They can also be configured to be permanently imported for all new sessions.
  • PowerShell functions, or Cmdlets, are commands that can be used in a session.
  • Functions with parameters allow for tab-complete—type a dash and Tab (or Ctrl + space) to see the available parameters for the function.
  • PowerShell can have pipeline-able objects that allow you to use the output from one function for the input of other functions.
  • The PowerShell pipeline is very powerful, and we will make extensive use of it in our examples.

We will be using several PowerShell-based tools throughout the book, and while we will try to make commands as simple as possible, it would be a good idea to get a basic understanding of how to use PowerShell.

Important note

If you're looking for non-book PowerShell resources, Microsoft does provide some free learning resources for those learning about PowerShell. These resources are a great beginner's course and will give you a head start on the concepts covered in this book: https://docs.microsoft.com/en-us/powershell/scripting/learn/more-powershell-learning.

For starters, you will need to be able to enable PowerShell script execution on your system. Chances are good that you will have some PowerShell execution policy restrictions on your testing system. As noted in this blog post by one of this book's technical reviewers, Scott Sutherland, these execution restrictions are easily bypassed (see https://blog.netspi.com/15-ways-to-bypass-the-powershell-execution-policy/).

For the installation of PowerShell modules, we will primarily use the PowerShell Gallery packages. The PSGallery (https://www.powershellgallery.com/) is a trusted, Microsoft-managed resource for package management. This is one of the easiest ways to install modules, and the Microsoft packages required for the toolkits will all be listed in the gallery.

Since we will walk through the installation of the Azure PowerShell modules in the second chapter of this book, the installation of these modules on your current system is not immediately needed.

The Az module

The Az PowerShell Cmdlets are functions that interact with Azure to allow for the administration of Azure services. These functions allow functions for listing, creating, destroying, and modifying Azure resources. While some Azure services are not supported by the functions, most services that you interact with will be supported.

  1. In an elevated (Run as Administrator) PowerShell session, run the Az module installation command, as follows:
    PS C:\> Install-Module -Name Az
  2. After installation, you will want to authenticate to your Azure tenant. You can do this by running the following code:
    PS C:\> Connect-AzAccount
  3. Much like the Azure CLI, this will prompt you to log in, but this time, an Azure AD Authentication Library (ADAL) authentication window will prompt you, instead of a web browser, as illustrated in the following screenshot:
Figure 1.14 – Az PowerShell authentication prompt

Figure 1.14 – Az PowerShell authentication prompt

From here, any command that you will use will be based off of the Microsoft guidance for approved verbs for PowerShell functions (https://docs.microsoft.com/en-us/powershell/scripting/developer/cmdlet/approved-verbs-for-windows-powershell-commands).

Most of the verbs that we will use are Get or Invoke, but this would be a good opportunity to try out the PowerShell tab completion.

  1. If the module is not already imported into your PowerShell session, import the Az module, as follows:
    PS C:\> Import-Module Az
  2. Then, type Get-Az, as follows, and pause:
    PS C:\> Get-Az
  3. From here, you can use the Ctrl + space shortcut to expand your options, as follows:
    Figure 1.15 – Az PowerShell module command options

    Figure 1.15 – Az PowerShell module command options

  4. If we do the same for a PowerShell function parameter, you will get all of the available parameters for the function, as follows:
    Figure 1.16 – Az PowerShell module parameter options

    Figure 1.16 – Az PowerShell module parameter options

  5. To see the sub-modules within the Az module, we can use the following command:
    PS C:\> Get-Module -Name az*
    Figure 1.17 – Listing Az PowerShell sub-modules

    Figure 1.17 – Listing Az PowerShell sub-modules

  6. To get all of the commands available in a module, you can use the following command:
    PS C:\> Get-Module -Name az*
Figure 1.18 – Listing Az.Accounts module commands

Figure 1.18 – Listing Az.Accounts module commands

Many of the actions that we try to accomplish in the PowerShell cmdlets can easily be found through tab completing. When in doubt, start typing what you think the command might be, and you may be surprised with how easy it is to find the real command.

Modules – Az versus AzureRM

If you're searching around the internet for a specific Az PowerShell function to use, you may run into functions prefixed with Azure Resource Manager (AzureRM), as compared to Az. These functions are for the now-deprecated AzureRM module. This is one of the original PowerShell modules for Azure administration, so you may run into references to it.

For most AzureRM functions, you should be able to substitute Az for AzureRM to get the equivalent Az module command (Get-AzureRmVM versus Get-AzVM).

The AzureAD module

The AzureAD module covers specific functions for managing Azure AD tenants. From a penetration-testing perspective, we will primarily be using this to enumerate information about an Azure AD tenant, but there are some privileged commands that can be used to add or modify users. Much like the Az module, this module will be required for some of the tools mentioned in the book. We will also install this module in our testing VM in the following section but will cover basic usage of the module here:

  1. In an elevated (Run as Administrator) PowerShell session, run the AzureAD module installation command, as follows:
    PS C:\> Install-Module -Name AzureAD
  2. After installation, you will want to authenticate to your Azure tenant. You can do this by running the following code:
    PS C:\> Connect-AzureAD

Just as with the Az module, this will prompt you to log in with an authentication window, and you can use the same PowerShell commands as you did with the Az module to help navigate the available functions.

Azure REST APIs

The final method for accessing Azure is by using the REST APIs. APIs are one of the few ways that we can make use of stolen access tokens, and we will be seeing examples of this in attack scenarios that we will cover in later chapters. REST clients such as Postman or cURL can be used to interact with the APIs if a valid authorization token is provided. In the later examples, we will also be using the HTTPie command-line tool for interacting with the APIs.

We could potentially write an entire chapter on using the REST APIs to manage Azure, but for now, just know that these are very powerful APIs that can be used to execute many of the same actions that we would normally take with the CLI or PowerShell modules.

If you want to play around with the REST API basics, check out the tutorials on the Microsoft Azure REST API reference page, at https://docs.microsoft.com/en-us/rest/api/azure/.

Azure Resource Manager

Regardless of the tool or method that we are using to interact with the Azure platform and Azure resources, the communication happens through a single central endpoint called Azure Resource Manager (ARM). You can think of it as a centralized layer for resource management in Azure (see Figure 1.19). The advantage of this approach is that there is consistency regardless of the tool that we are using. Authentication and access are all handled the same way.

When we make a request for an operation to be performed, using any of the tools that we described earlier, Resource Manager will talk to ''resource providers'' that perform the action we've requested, as illustrated in the following diagram:

Figure 1.19 – ARM

Figure 1.19 – ARM

Resource providers are services that provide different types of resources. For example, the network resource provider is responsible for network resources (virtual networks, network interfaces, and so on), while the compute resource provider is responsible for compute resources (VMs).

 

Summary

While it may not be the most exciting chapter of the book, the Azure platform fundamentals will set the stage for the rest of the attacks that we are going to learn. As we continue into the following chapters, keep in mind the underlying structure of Azure from both resource and RBAC perspectives.

In the next chapter, we will walk you through the setup of an Azure environment and a penetration-testing VM that you can use to simulate the attack scenarios we will be covering in the rest of the book.

 

Further reading

This is a great read to understand how to implement security for your Azure environment and services:

  • Microsoft Azure Security Technologies Certification and Beyond by David Okeyode

About the Authors

  • David Okeyode

    David Okeyode is a cloud security architect at the Prisma cloud speedboat at Palo Alto Networks. Before that, he was an independent consultant helping companies secure their cloud environments through private expert-level training and assessments. He holds 15 professional certifications across the Azure and AWS platforms, including the Azure Security Engineer, Azure DevOps, and AWS Security Specialist certifications. He has also authored two cloud computing courses for the popular cybersecurity training platform Cybrary.

    David has over a decade of experience in cybersecurity (consultancy, design, and implementation) and over 6 years of experience as a trainer. He has worked with organizations of different sizes, from start-ups to major enterprises to government organizations.

    David has developed multiple vulnerable-by-design automation templates that can be used to practice cloud penetration testing techniques. He regularly speaks about cloud security at major industry events, such as Microsoft Future Decoded and the European Information Security Summit.

    David is married to a lovely girl who makes the best banana cake in the world. They love traveling the world together and intend to do missions in Asia very soon!

    Browse publications by this author
  • Karl Fosaaen

    As a Practice Director at NetSPI, Karl leads the Cloud Penetration Testing service line and oversees NetSPI’s Portland, OR office. Karl holds a BS in Computer Science from the University of Minnesota and has over a decade of consulting experience in the computer security industry. Karl spends most of his research time focusing on Azure security and contributing to the NetSPI blog. As part of this research, Karl created the MicroBurst toolkit on GitHub to house many of the PowerShell tools that he uses for testing Azure.

    Browse publications by this author
Penetration Testing Azure for Ethical Hackers
Unlock this book and the full library for FREE
Start free trial