aidenpearce369
Published on

Offsec AD (Part 4) : AD Structure & Automation via Active Direcory Module

Prologue

Welcome to our comprehensive guide on creating a well-structured Active Directory (AD) environment. In this blog, we'll delve into the world of AD objects, such as Organizational Units (OUs), Domain Computers, Domain Groups, and more. Understanding these components is crucial for setting up an efficient, organized, and secure AD infrastructure. So, let's explore the significance of each AD object and the myriad benefits they bring to your network administration.

Why Active Directory

An unorganized network lacks structure, manual management, security risks, and challenges in troubleshooting and user experience which is poor for establishing an enterprise and maintaining control in it.

Unorganized

A Active Directory domain can have vital features like hierarchical structure with centralized management, enhanced security, and efficient user experience. Using Active Directory (AD) for an enterprise offers other numerous benefits, making it an essential component of modern network administration. Here are some of the reasons why AD is crucial for enterprises and the advantages it provides:

Organized

  • Centralized User Management: AD allows central management of user accounts, making it easy to create, modify, and delete user accounts across the entire network. This centralized approach simplifies user administration and reduces the risk of errors.

  • Single Sign-On (SSO): With AD, users can log in once and gain access to various resources and services within the network without having to re-enter credentials multiple times. This improves user experience and enhances productivity.

  • Security and Access Control: AD provides a robust security model that allows administrators to define granular access controls. It ensures that users have appropriate access rights to resources based on their roles and responsibilities, reducing the risk of unauthorized access and data breaches.

  • Group Policy Management: Group Policy in AD allows administrators to enforce security settings, software deployment, and configuration settings across all domain-joined computers. This ensures a standardized and secure computing environment.

  • Network Resource Management: AD enables efficient management of network resources such as printers, file shares, and applications. It simplifies resource sharing, access control, and permissions management.

  • Scalability and Flexibility: AD is highly scalable and can accommodate thousands of users and devices. As an organization grows, AD can easily adapt to the changing network requirements.

  • Fault Tolerance and Redundancy: AD supports multi-domain and multi-site configurations, providing fault tolerance and redundancy. This ensures high availability and reliability of directory services even in the event of server failures.

  • Integration with Other Services: AD integrates seamlessly with various Microsoft services like Exchange Server, SharePoint, and Microsoft 365. This integration simplifies user management and enhances the overall user experience.

  • Audit and Compliance: AD offers extensive auditing capabilities, allowing administrators to track changes and access to resources. This helps meet compliance requirements and aids in identifying security issues.

  • Remote Management: AD provides remote management capabilities, allowing administrators to manage users, computers, and resources across geographically dispersed locations from a central console.

  • Authentication and Encryption: AD uses secure authentication protocols and encryption methods to protect user credentials and communication between clients and servers, ensuring data confidentiality and integrity.

  • Support for Multi-Platform Environments: While AD is primarily associated with Windows environments, it can also be integrated with non-Windows platforms, providing a single authentication source for a diverse IT infrastructure.

Overall, Active Directory plays a critical role in enhancing network security, streamlining administration, and improving the overall efficiency and productivity of enterprises. It remains a cornerstone of modern IT infrastructure and is indispensable for organizations of all sizes.

Active Directory Module

The Active Directory Module is a software component or set of tools that provides administrators with a powerful and efficient way to manage Active Directory (AD) from the command line or PowerShell scripting environment. It offers a collection of cmdlets (command-lets) that enable administrators to perform various AD-related tasks programmatically, making it an essential tool for automating and streamlining administrative tasks. In a Domain Controller, the Active Directory Module is usually already installed by default as part of the Active Directory Domain Services (AD DS) role.

The Active Directory Module is primarily used in environments where PowerShell is the preferred scripting and automation language. It is available as part of the Remote Server Administration Tools (RSAT) on Windows Server operating systems and can also be installed on Windows client machines.By leveraging the Active Directory Module in PowerShell scripts, administrators can save time, reduce errors, and enhance the overall efficiency of Active Directory management in their organization. It is a valuable tool for any IT professional working with Active Directory on Windows-based systems.

To open PowerShell with Active Directory Module, select Active Directory Module with Windows PowerShell.

Powershell-ADModule

Querying Domain Users and Domain Computers using Active Directory Module.

Queryin-ADModule

Active Directory module can also be imported on native PowerShell command line.

Import-ADModule

Structure of Active Directory

Active Directory (AD) is a hierarchical database that organizes and stores information about network resources such as users, computers, groups, and more. The structure of AD is based on a hierarchical model, which allows for efficient organization, delegation of administrative tasks, and easy management of network resources. The primary building blocks of AD's hierarchical structure are Organizational Units (OUs). And there are other AD objects as well, like Domain Users, Domain Computers, Domain Groups, GPOs, Printers and File Shares etc.

Objects in Active Directory

In Active Directory, objects represent various elements within the directory that store information about different resources in a network environment. The most common objects in Active Directory include:

  • Organizational Units (OUs): Represents containers used to organize objects within the directory. OUs are used to create a hierarchical structure for better management and delegation of administrative tasks.

  • Users: Represents individual users in the network. User objects store information about each user, such as their name, login credentials, contact details, and group memberships.

  • Computers: Represents computer systems joined to the domain. Computer objects store information about each computer, such as its name, operating system, and network settings.

  • Groups: Represents collections of users or computers with similar characteristics. Group objects are used to simplify access control and permissions management. There are two types of groups: security groups (used for access control) and distribution groups (used for email distribution lists).

  • Group Policy Objects (GPOs): Represents policy settings that define the behavior and configuration of users and computers within the domain. GPOs are linked to OUs to apply specific settings to objects within those OUs.

  • Domains: Represents a logical grouping of objects within a network. Domains form the core unit of logical organization in Active Directory and can contain users, computers, and groups.

  • Printers: Represents network printers within the domain. Printer objects store information about printer settings and configurations.

  • Contacts: Represents external entities, such as individuals or organizations, that may not be part of the domain but need to be included in the global address list for communication purposes.

These objects work together to create a structured and organized directory that composes the working environment in a Active Directory.

Organizational Units

OUs are containers within AD that group objects based on their organizational or administrative needs. They serve as logical subdivisions of the domain and help in the organization and management of resources. OUs allow administrators to delegate control and apply Group Policy settings to specific groups of objects, enhancing security and simplifying administration.

Creating a new Organizational Unit (OU) within our domain.

OU-0

OU-1

We can see that the OU we have created gets listed successfully. The distinguished name OU=NewParentOU,DC=pwners,DC=lab has different segments, where the first part OU denotes the Organizational Unit (OU) and the second part DC denotes the Domain Controller.

NOTE : The Distinguished Name (DN) attribute represents the unique name of the OU within the Active Directory hierarchy. It is used to uniquely identify the OU in the directory.

OU-2

Creating a new child OU within the parent OU via Active Directory module in commmand line.

OU-3

Domain Computers

A Domain Computer refers to a computer that has been joined to an Active Directory (AD) domain. When a computer is connected to a domain, it becomes a member of the domain and gains the ability to participate fully in the Active Directory environment and it establishes a secure relationship with the domain controller. Connecting a computer to a domain offers numerous technical benefits, including centralized user management, group policy enforcement, secure authentication and maintain resource access control.

Creating a computer within the newly created OU of our domain.

1Computer-1

Computer-2

Listing Domain Computers using Active Directory module.

Computer-3

Creating domain computer via Active Directory module in PowerShell command line

Computer-4

Domain Users

Domain users are user accounts created within an Active Directory (AD) domain. When a user account is created in the AD domain, it becomes a part of the domain's security and authentication infrastructure. Users can then log in to domain-joined computers and access network resources based on their permissions granted by the domain administrator.

Creating an user within the newly created OU of our domain.

User-1

The newly created user will be part of Domain Users group by default. The same goes to Domain Computers as well while joining a new computer in the domain.

User-2

Domain Groups

Domain groups are collections of user accounts, computer accounts, or other groups within an Active Directory (AD) domain. They serve as a way to logically organize and manage users and resources in the network environment. Domain groups simplify the process of granting permissions and applying policies to multiple users or computers at once, making it more efficient for administrators to manage access and security within the AD domain.

Creating a group within the newly created OU of our domain.

Group-1

Group-2

Querying Domain Groups via Active Directory module in PowerShell.

Group-3

Adding members to the newly created group in the OU of our domain.

Group-4

Group-5

Group-6

Listing the members present in the group via Active Directory module in PowerShell.

Group-7

Deleting Organizational Unit (OU)

In Active Directory, Organizational Units (OUs) cannot be deleted by default as a security measure to prevent accidental data loss and to maintain the integrity of the directory structure. Deleting an OU could result in the loss of all the objects contained within it, leading to potential data loss and disruptions to the network environment.

Del-OU1

Del-OU2

Accidental Deletion Prevention is a feature in Active Directory that helps protect critical objects, including Organizational Units (OUs), from being accidentally deleted by authorized users. When this feature is enabled for an OU, it adds an extra layer of security to prevent unintentional data loss due to accidental deletion. To delete a OU, accidental deletion prevent should be disabled for the objetct.

Enable the Advaced Features in the properties.

Del-OU3

Disable the accidental deletion attribute for the object.

Del-OU4

While deleting it confirm the prompt to perform the same action over its sub-tree.

Del-OU5

Now the OU objects should be deleted from our Active Directory domain.

Del-OU6

Automation via Active Directory Module

By leveraging the Active Directory module in PowerShell, we can easily automate the creation of Organizational Units (OUs), Users, Computers, and Groups. Using automation in a domain environment we can increase the efficiency in the administrative process and save our valuable time.

The below code automates the task of creating users, computers and groups via Active Directory module.

# Import the Active Directory module
Import-Module ActiveDirectory

# User Dictionary
$userDictionary = @{
    # Developers
    "User1" = @{
        FirstName = "Pwner"
        LastName = "Developer1"
        SamAccountName = "pwner.developer1"
        DisplayName = "Pwner Developer1"
        Description = "Automated developer user via PowerShell"
        Password = "DevP@ssw0rd1"
        OuPath = "OU=Developers,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    "User2" = @{
        FirstName = "Pwner"
        LastName = "Developer2"
        SamAccountName = "pwner.developer2"
        DisplayName = "Pwner Developer2"
        Description = "Automated developer user via PowerShell"
        Password = "DevP@ssw0rd2"
        OuPath = "OU=Developers,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    "User3" = @{
        FirstName = "Pwner"
        LastName = "Developer3"
        SamAccountName = "pwner.developer3"
        DisplayName = "Pwner Developer3"
        Description = "Automated developer user via PowerShell"
        Password = "DevP@ssw0rd3"
        OuPath = "OU=Developers,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    "User4" = @{
        FirstName = "Pwner"
        LastName = "Developer4"
        SamAccountName = "pwner.developer4"
        DisplayName = "Pwner Developer4"
        Description = "Automated developer user via PowerShell"
        Password = "DevP@ssw0rd4"
        OuPath = "OU=Developers,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    # Testers
    "User5" = @{
        FirstName = "Pwner"
        LastName = "Tester1"
        SamAccountName = "pwner.tester1"
        DisplayName = "Pwner Tester1"
        Description = "Automated tester user via PowerShell"
        Password = "TestP@ssw0rd1"
        OuPath = "OU=Testers,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    "User6" = @{
        FirstName = "Pwner"
        LastName = "Tester2"
        SamAccountName = "pwner.tester2"
        DisplayName = "Pwner Tester2"
        Description = "Automated tester user via PowerShell"
        Password = "TestP@ssw0rd2"
        OuPath = "OU=Testers,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    "User7" = @{
        FirstName = "Pwner"
        LastName = "Tester3"
        SamAccountName = "pwner.tester3"
        DisplayName = "Pwner Tester3"
        Description = "Automated tester user via PowerShell"
        Password = "TestP@ssw0rd3"
        OuPath = "OU=Testers,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    "User8" = @{
        FirstName = "Pwner"
        LastName = "Tester4"
        SamAccountName = "pwner.tester4"
        DisplayName = "Pwner Tester4"
        Description = "Automated tester user via PowerShell"
        Password = "TestP@ssw0rd4"
        OuPath = "OU=Testers,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    # Exploiters
    "User9" = @{
        FirstName = "Pwner"
        LastName = "Exploiter1"
        SamAccountName = "pwner.exploiter1"
        DisplayName = "Pwner Exploiter1"
        Description = "Automated exploiter user via PowerShell"
        Password = "ExpP@ssw0rd1"
        OuPath = "OU=Exploiters,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    "User10" = @{
        FirstName = "Pwner"
        LastName = "Exploiter2"
        SamAccountName = "pwner.exploiter2"
        DisplayName = "Pwner Exploiter2"
        Description = "Automated exploiter user via PowerShell"
        Password = "ExpP@ssw0rd2"
        OuPath = "OU=Exploiters,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    "User11" = @{
        FirstName = "Pwner"
        LastName = "Exploiter3"
        SamAccountName = "pwner.exploiter3"
        DisplayName = "Pwner Exploiter3"
        Description = "Automated exploiter user via PowerShell"
        Password = "ExpP@ssw0rd3"
        OuPath = "OU=Exploiters,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    "User12" = @{
        FirstName = "Pwner"
        LastName = "Exploiter4"
        SamAccountName = "pwner.exploiter4"
        DisplayName = "Pwner Exploiter4"
        Description = "Automated exploiter user via PowerShell"
        Password = "ExpP@ssw0rd4"
        OuPath = "OU=Exploiters,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
}

# Computers
$computerDictionary = @{
    "Computer1" = @{
        Name = "pwner-devdesk1"
        OuPath = "OU=Developers,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    "Computer2" = @{
        Name = "pwner-devdesk2"
        OuPath = "OU=Developers,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    "Computer3" = @{
        Name = "pwner-testerdesk1"
        OuPath = "OU=Testers,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    "Computer4" = @{
        Name = "pwner-testerdesk2"
        OuPath = "OU=Testers,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    "Computer5" = @{
        Name = "pwner-expdesk1"
        OuPath = "OU=Exploiters,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
    "Computer6" = @{
        Name = "pwner-expdesk2"
        OuPath = "OU=Exploiters,OU=PwnersLabOrg,DC=pwners,DC=lab"
    }
}

# Group Dictionary
$groupData = @{
    "dev Group" = @("pwner.developer1", "pwner.developer2","pwner.developer3","pwner.developer4")
    "tester Group" = @("pwner.tester1", "pwner.tester2","pwner.tester3","pwner.tester4")
    "expdev Group" = @("pwner.exploiter1","pwner.exploiter2","pwner.exploiter3","pwner.exploiter4")
}

# OUs
$ouNameList = @(
    "Testers",
    "Developers",
    "Exploiters"
)

# Creating OUs
$parentContainerDN = "OU=pwnersLabOrg,DC=pwners,DC=lab"
foreach ($ouName in $ouNameList) {
    if (Get-ADOrganizationalUnit -Filter { Name -eq $ouName }) {
        Write-Host "[-] OU '$ouName' already exists."
    } else {
        try {
            New-ADOrganizationalUnit -Name $ouName -Path $parentContainerDN -Description "OU created via PowerShell automation"
            Write-Host "[+] OU '$ouName' created successfully."
        } catch {
            Write-Host "[-] Error creating OU: $_.Exception.Message"
        }
    }
}

# Create Users 
foreach ($userData in $userDictionary.GetEnumerator()) {
    $userProperties = $userData.Value
    $samAccountName = $userProperties.SamAccountName
    if (Get-ADUser -Filter { SamAccountName -eq $samAccountName }) {
        Write-Host "[-] User '$($userProperties.SamAccountName)' already exists."
    } else {
        try {
            New-ADUser -SamAccountName $userProperties.SamAccountName `
                       -Name $($userProperties.FirstName+" "+$userProperties.LastName) `
                       -UserPrincipalName "$($userProperties.SamAccountName)@pwners.lab" `
                       -GivenName $userProperties.FirstName `
                       -Surname $userProperties.LastName `
                       -DisplayName $userProperties.DisplayName `
                       -Description $userProperties.Description `
                       -Enabled $true `
                       -AccountPassword (ConvertTo-SecureString $userProperties.Password -AsPlainText -Force) `
                       -ChangePasswordAtLogon $true `
                       -Path $userProperties.OuPath

            Write-Host "[+] User '$($userProperties.SamAccountName)' created successfully."
        } catch {
            Write-Host "[-] Error creating user $($userProperties.SamAccountName): $_.Exception.Message"
        }
    }
}

# Create Computers
foreach ($computerData in $computerDictionary.GetEnumerator()) {
    $computerProperties = $computerData.Value
    $computerName = $computerProperties.Name
    if (Get-ADComputer -Filter { Name -eq $computerName }) {
        Write-Host "[-] Computer '$($computerProperties.Name)' already exists."
    } else {
        try {
            New-ADComputer -Name $computerProperties.Name -Path $computerProperties.OuPath -Description "New computer created with PowerShell"
            Write-Host "[+] Computer '$($computerProperties.Name)' created successfully."
        } catch {
            Write-Host "[-] Error creating computer '$($computerProperties.Name)': $_.Exception.Message"
        }
    }
}

#Create Groups
$ouPath = "OU=PwnersLabOrg,DC=pwners,DC=lab"  # Replace with the desired OU path
foreach ($group in $groupData.GetEnumerator()) {
    $groupName = $group.Key
    $groupMembers = $group.Value
    if (Get-ADGroup -Filter { Name -eq $groupName }) {
        Write-Host "[-] Group '$groupName' already exists."
    } else {
        try {
            $newGroup = New-ADGroup -Name $groupName -GroupCategory Security -GroupScope Global -Path $ouPath -Description "New domain group created with PowerShell"
            Write-Host "[+] Group '$groupName' created successfully."
            foreach ($member in $groupMembers) {
                $user = Get-ADUser -Filter { SamAccountName -eq $member }
                if ($user) {
                    Add-ADGroupMember -Identity $groupName -Members $member
                    Write-Host "[+] Added user '$member' to group '$groupName'."
                } else {
                    Write-Host "[-] User '$member' not found. Skipping adding to group '$groupName'."
                }
            }
        } catch {
            Write-Host "[-] Error creating group '$groupName': $_.Exception.Message"
        }
    }
}

By running this automation script, we can see that the defined AD objects got created successfully.

Automation-1

Automation-2

Automation-3

Automation-4

Automation-5

Conclusion

By utilizing AD objects such as OUs, Domain Computers, Domain Groups, and Users, you can streamline network administration, enhance security, and simplify access control. Implementing best practices and security considerations will ensure the longevity and efficiency of your AD infrastructure. For now we have created a Active Directory domain with a minimal functional replica of an organization which will be suitable for pentesting. In the following blogs, we will be deep diving into technical content related to Active Directory.