Penetration Testing Lab Setup - Syncing On-Prem AD with Azure

Dec 30, 2023 · 14 mins read
Penetration Testing Lab Setup - Syncing On-Prem AD with Azure

Overview

My journey into building a penetration testing lab started with setting up an on-premises Active Directory. This step was crucial, not just for getting AD running but also for ensuring it would sync smoothly with Azure AD later. With a Microsoft 365 Sandbox already set up and filled with users, my next move was to merge my Azure student subscription with this environment.

After getting the domain controller up and connected, I synced it with Azure AD, preparing for future tests and scenarios. To make the setup more akin to a small corporate network, I also set up several Windows VMs in Azure, each acting as a part of this domain.

This lab is my workspace for sharpening my skills in penetration testing/red teaming and cloud security. I’m documenting my process to provide a clear, straightforward guide for anyone interested in exploring security and cloud security. Whether you’re new to security testing or looking to improve your cloud security knowledge, this post is meant to help you replicate a similar setup and start your own exploration into cybersecurity.

M365 Sandbox and Moving My Student Subscription over

I registered for the Microsoft 365 Developer Program, a process that’s quite user-friendly and accessible to anyone.

This is the video I watched on how to migrate my Student Subscription to my M365 Sandbox account

Issues I encountered

During my setup, I encountered a AD synchronization issue due to a mismatch between the UPN suffixes in my on-premises Active Directory and the domain name in my Azure AD tenant. To remediate this, I added a new UPN suffix to my on-prem AD that matched my Azure AD tenant domain and updated every user’s UPN manually. To prevent such issues, it’s advisable to ensure that your domain controller’s domain name is the same as your Azure AD tenant domain. Since I am using the M365 sandbox provided to me, it comes with a pre-configured Azure domain in the format of [TENANT].onmicrosoft.com, which I should have mirrored in my on-prem setup from the start.

No worries if your domain names don’t initially match, I detailed how to fix this issue in this post.

Domain Controller Set Up

I used my student benefits on Azure to obtain the Windows Server 2022 Standard edition for free. After downloading the ISO, I set it up as a boot volume in VMware Workstation and proceeded to install Windows Server, configuring it as a Domain Controller.

Configuring Services

Now that I am logged into to the machine, its time to promote it to Domain Controller. Let’s launch the Server Manager and click on Add roles and features option.

On the next tab Installation Type, I just choose Role-based or feature-based installation option and click Next.

On the next tab Server Selection, ensure Select a server from the server pool is selected.

On the Server Roles tab, check the Active Directory Domain Service checkbox.

This will display the following dialog, in which you just confirm that you are ok with installing additional features that Active Directory Domain Services (ADDS) will need to install. Select the Add Features option.

Click Next.

You can click Next on the AD DS tab.

Click Install on the Confirmation tab.

This will start the installation and will take some time. Once the installation is complete, you can just click on Close.

Promoting VM to Domain Controller

It will then display a warning flag, as illustrated in the figure below. When you click on the flag, a link to Promote this server to a domain controller will appear. Click on that link.

The Active Directory Domain Service Configuration Wizard is launched when you click the Promote this server to a domain controller link. The first tab, Deployment Configuration, displays different deployment operations. Let’s go with the Add a new forest option.

I will be naming it SECURITYLABS.local and clicking Next.

On the Domain Controller Options tab, enter a password for DSRM and click Next.

Click Next on DNS Options tab.

The NetBIOS domain name should populate automatically. Click Next.

Accept all the defaults on the Paths tab and just click Next.

Review the options and click Next.

Got this error while the Prerequisites Check was running:

Verification of prerequisites for Domain Controller promotion failed. The local Administrator account becomes the domain Administrator account when you create a new domain. The new domain cannot be created because the local Administrator account password does not meet requirements.

Currently, the local Administrator password is blank, which might lead to security issues. We recommend that you press Ctrl+Alt+Delete, use the net user command-line tool, or use Local Users and Groups to set a strong password for the local Administrator account before you create the new domain.

To fix this:

Go to Computer Management -> Local Users and Groups and click Administrator user and click Set Password and rerun the prerequisite check.

Rerun the Prerequisites Check - On the final step, click Install button.

It will take a few minutes for this installation to complete. This will cause a reboot of the machine as well. After that, you can log in with the domain credentials.

Rename Computer

Renaming the PC name to something more convenient.

Configuring Certificate Services

The following steps are to configure Certificate Services.

Let’s relaunch the Server Manager and select the Add roles and features option.

This will start the Add Roles and Features Wizard, which we previously utilized. Continue to click Next until you reach the Server Roles tab. Select Active Directory Certificate Services (ADCS) here.

That will pop-up the following dialog with the information about the required features for ADCS. Click on Add Features button.

Click on the Next button.

Click on the AD CStab.

Check the Restart the destination server automatically if required checkbox on the Confirmation tab. A confirmation dialog will appear. Click Next after selecting Yes.

This will begin the installation of ADCS and the necessary components.

You will see a warning flag. Click on that flag, then on the link for Configure Active Directory Certificate Services on the destination server.

This will launch the AD CS Configuration wizard. Click next on the Credentials tab.

On the Role Services tab, check the Certification Authority check box and click Next.

Make sure to select Enterprise CA on the Setup Type tab and click Next. But in my case, I am unable to. This is most likely because I am not not running the installation with an account that is a local administrator on the server or is not a member of the Enterprise Admins group or the Domain Admin group.

To fix this, in `Server Manager``

Go to Tools > Active Directory Users and Computers > $DOMAINNAME > Users > Select Current User > Member Of > Add … > Domain Admin + Enterprise Admin > Log out and back in

Open CMD Prompt to confirm:

net user $username /domain

To enable the the Enterprise option, simply add the user account to one of the groups listed above and log out and in again (to update the Kerberos token) or use an account that already is a member, then retry the installation.

Continuing:

Make sure to select Root CA on the CA Type tab and click Next.

Select Create a new private key on the Private Key tab and click Next.

Stay with the default options on the Cryptography tab and click Next.

Keep all the default names of CA Name tab and click Next.

On the Validity Period, Click Next

Keep the the default database and log location and click Next.

Click the Configure button on the Confirmation tab.

Shortly after you will see the message about Configuration succeeded. You can close this dialog now.

Restart the VM now so the changes take effect.

Automating AD User and Group Creation with PowerShell

I wanted automate the creation of users and groups. Manual creation can be tedious and time-consuming, so leveraging PowerShell speeds up the process.

Here’s how I scripted the setup of organizational units (OUs) and groups within Active Directory using PowerShell scripting.

Creating Groups OU

First we need to launch the Server Manager and click on the Active Directory Users and Computers menu option as shown below.

This will launch the Active Directory Users and Computers application, displaying my domain, SECURITYLAB.local.

I then right-clicked on the SECURITYLABS.local node (or whatever your domain is named) and selected the option to create a new OU.

In the dialog that appeared, I named the new OU “Groups.”

PowerShell Script to Create new Groups

Before sanything, ensure that the Active Directory PowerShell Module is installed and imported.

Import-Module ActiveDirectory

I then opened and ran PowerShell ISE as an Administrator and prepared my environment.

With the module ready, I crafted a script to create various groups typically found in an organization (Modify ):

# List of groups
$groups = @("HR", "IT", "Sales", "Finance", "Helpdesk", "Security Admins", "IT Network", "IT Support", "IT Development")

foreach ($group in $groups) {
    # Create each group in Active Directory
    New-ADGroup -Name $group -GroupScope Global -Path "OU=Groups,DC=SECURITYLABS,DC=local" # Update the path as needed
}

This script is flexible — easily modified to fit different needs or to add more groups. By automating this process, I’ve saved time and ensured a consistent setup across my lab environment.

Go back and check your Groups OU

PowerShell Script to Create New Users

To efficiently populate my lab with a realistic user environment, I generated a list of random 20 users with passwords. I decided on a naming convention for the usernames: {f}{last}@securitygroups.local, which means the first letter of the first name followed by the full last name.

I saved the usernames and passwords into seperate .csv files.

To automate the creation of these user accounts in Active Directory, I used PowerShell, a powerful tool that saved me from the tedium of manual input. Here’s how I did it:

Import-Module ActiveDirectory

# Import user data from a CSV file
$Users = Import-csv "C:\path\to\users.csv" # Adjust the path to your .csv file

# Loop through each user in the CSV
foreach ($User in $Users) {
    # Create the user logon name from the first letter of the first name and the full last name
    $userLogonName = ("{0}{1}" -f $User.FirstName[0], $User.LastName).ToLower()

    # Prepare user properties for account creation
    $userProps = @{
        SamAccountName         = $userLogonName
        UserPrincipalName      = "$userLogonName@SECURITYLABS.local"
        Name                   = "$($User.FirstName) $($User.LastName)"
        GivenName              = $User.FirstName
        Surname                = $User.LastName
        AccountPassword        = (ConvertTo-SecureString -AsPlainText -Force -String "AComplexPassword!") # Replace with dynamic password if available
        Path                   = "OU=Users,DC=SECURITYLABS,DC=local" # Adjust to match your AD structure
        Enabled                = $true 
        ChangePasswordAtLogon  = $false
    }

    # Attempt to create the new user account
    try {
        New-ADUser @userProps -Verbose
    } catch {
        Write-Host "Error creating user $userLogonName: $($_.Exception.Message)"
    }
}

After running this script, my AD was populated with 20 new users, each fitting into my predetermined naming structure. I made sure to securely dispose of any user and password files and cleared my PowerShell history. Finally, I saved a snapshot of my setup to preserve this state.

AD Synchronization

The first step is to download Azure AD Connect - I visited Microsoft’s official download page and downloaded Azure AD Connect onto my domain controller.

Azure AD Connnect Configuration Wizard

With the installation file ready, I launched the Azure AD Connect wizard, selecting customized for my installation type.

On the Required Components tab I just clicked Install.

On the next tab - User Sign-In - I selected Password Hash Synchronization and Enable single sign-on. Password Hash Synchronization (PHS) is a feature provided by Azure AD Connect that enables the synchronization of user password hashes from an on-premises Active Directory environment to the Azure AD cloud.

Authenticating to Azure

Next, I needed to authenticate with Azure. I used my Global Admin user to connect to the Azure AD Tenant I wanted to sync with.

UPN Suffix Issues

This is where I encountered the UPN suffix issue. This is where my UPN Suffixes were not matching up between my on-prem AD and Azure AD.

I started by logging into the Azure portal to grab my domain name. In the Azure Active Directory service, I found my domain formatted as $yourtenantname.onmicrosoft.com.

Went back to my on-prem domain controller. I opened the Server Manager and navigated to the Active Directory Domains and Trusts.

Right-clicked the root node displaying my AD forest name and selected Properties.

In the UPN Suffixes tab, add $yourtenantname.onmicrosoft.com into the Alternative UPN suffixes box and click Add.

Now we need to change each users UPN suffix to the newly added one. To do this, from Server Manager, open Active Directory Users and Computers (ADUC). For each user:

Navigate to the OU where your users are located, right click and go to their Properties and then to the Account tab.

Select the new UPN suffix from the dropdown next to the User logon name.

Click Apply and OK.

Make sure to verify the changes, just reopen the properties of a few accounts to check that the new UPN suffix is displaying correctly.

Rerunning Azure AD Connect Configuration Wizard

I relaunched the Azure AD Connect wizard and followed the steps I’d previously taken. When I reached the Azure AD Sign-in tab, I checked for my new AD UPN Suffix.

My UPN suffix was listed as “Not Added” under the Azure AD Domain, no issue. Just continue by selecting “Continue without matching all UPN suffixes to verified domains” at the bottom and click Next.

In the Domain and OU filtering tab, I made sure my directory was selected. If `$yourtenantname.onmicrosoft.com`` was missing, again, no worries; just select the original directory and moved forward.

For Uniquely identifying users tab, I clicked Next without making changes.

In the Optional features section, I selected ‘Password Writeback’. This feature allows for real-time password changes in the cloud to be written back to my on-premises directory.

In the Enable single sign-on section, I authenticated as my domain admin user from the on-prem AD and then clicked Next.

At the Ready to configure step, I ensured “Start the synchronization process when configuration completes” was selected and then clicked Install. This took some time, but once complete, a “Configuration complete” window confirmed the success.

To verify everything was synced you can either:

Open the Azure Synchronization Service Manager on your domain controller. Just make sure that your current user is in the ADSyncAdmins group with the correct permissions. Run the service manager as an admin and you should see your domain synced to Azure.

Or you can also navigate to your Azure Portal, go to Users, and there you should see your on-prem users listed.

Azure Setup

Resource Group Creation

Sharing is caring!