Использование power shell для эффективного управления active directory

In this guide, we will introduce the PowerShell Active Directory Module, exploring what it is, its role in simplifying management tasks, and how to install and import it efficiently.

We will start this series to talk about one of the most known built in tools in Microsoft, PowerShell. We will discuss its multitude of functions and its connection to many exploits within Active Directory.

In this blog series, we will embark on a journey through the intricate landscape of Active Directory, shedding light on the most prevalent pitfalls and vulnerabilities that organizations face. We will explore the potential consequences of these weaknesses and provide practical mitigation techniques to fortify your Active Directory environment against potential attacks.

Для контроля хода репликации объектов AD можно использовать средства PowerShell из модуля Active Directory.

Для начала, импортируем модуль:

Import-Module ActiveDirectory

Для выведения полного списка командлетов, связанных с работой по репликации AD можно выполнить:

get-command -module activedirectory -name *ADReplicat*

В случае, если нужно вывести список ошибок репликации на контроллере(или контроллерах) домена, можно воспользоваться командлетом

Get-ADReplicationFailure -Target DC1,DC2

, где DC1,DC2 – имена домен-контроллеров.

Также можно запросить статус репликации для всех контроллеров домена в составе сайта:

Get-ADReplicationFailure -scope site -target {SITE} | FT Server, LastError, Partner-Auto

Тоже самое, но для отдельного домена:

Get-ADReplicationFailure -Target "domen.com" -Scope Domain

Предположим, выявили проблемы с репликацией конкретного объекта AD. В этом случае можно попробовать принудительно инициировать его репликацию с помощью командлета Sync-ADObject.

​​​​​​​Get-ADDomainController -filter * | foreach {Sync-ADObject -Object "cn=Vasya Pupkin ,cn=Users,dc=domen,dc=com" -source DC1 -Destination $_.hostname}

Еще несколько полезных командлетов.

Get-ADReplicationPartnerMetadata ​​​​​​​позволяет получить информацию о метаданных репликации между DC и его партнерами, в частности время последней попытки выполнить репликацию и время последней успешной репликации( для этого нужно выбрать данные, которые мы хотим получить (Select-Object Server, LastReplicationAttempt, LastReplicationSuccess, Partner)

С помощью командлета Get-ADReplicationQueueOperation можно получить список операций ожидающих репликации на сервере.

Командлет Get-ADReplicationConnection позволяет вывести информацию о партнерах репликации для текущего контролера домена. Например, если мы хотим узнать эту информацию для конкретного домен-контроллера, можно выполнить:

Get-ADReplicationConnection -Filter {ReplicateToDirectoryServer -eq "DC1"}

Командлет Get-ADReplicationUpToDatenessVectorTable выдает список USN для партнеров по репликации:

Get-ADReplicationUpToDatenessVectorTable * | ft Partner,Server,UsnFilter


Ashkon Yasseri

Active Directory Security | Securing Enterprise Networks

In the world of IT, efficiency and automation are key. For professionals managing Active Directory (AD), Microsoft’s PowerShell offers a powerful toolset that can significantly enhance productivity and effectiveness. This post will delve into how IT professionals can leverage PowerShell for Active Directory management, providing practical examples and tips.

Active Directory and PowerShell

Active Directory is a directory service developed by Microsoft for Windows domain networks. It is included in most Windows Server operating systems and provides a variety of services, including LDAP, Kerberos-based authentication, DNS-based naming and other network services.

:/>  Нет звука в динамиках на компьютере windows 7

Practical PowerShell Commands for Active Directory Management

Here are some practical examples of how PowerShell can be used for AD management:

  1. ser -Filter * -Property
  2. ntity “IT Team” -Memb

Advanced Active Directory Management with PowerShell

Here are some examples of advanced PowerShell commands for AD management:

  1. Creating an Organizational Unit cmdlet allows you to create a new OU in AD. For example:
  2. New-ADOrganizationalUnit -Name “Sales” -Path “DC=yourdomain,DC=com”
  3. Managing Group Policy Objects: The Group Policy cmdlets in Windows PowerShell allow you to manage Group Policy Objects (GPOs). For example, you can create a new GPO and link it to an OU:
  4. Working with ADFS: If you’re using Active Directory Federation Services, you can use PowerShell to manage your ADFS configuration. For example, you can use the cmdlet to retrieve the properties of your ADFS service:

Tips for Using PowerShell with Active Directory

  1. Learn the Basics: Before diving into PowerShell for AD management, ensure you have a solid understanding of PowerShell basics, including cmdlets, variables, and scripts.
  2. Use the AD Module: The Active Directory Module for Windows PowerShell is a key tool that provides cmdlets for managing AD.
  3. Leverage Online Resources: There are many online resources, including Microsoft’s own documentation and various IT forums, that provide a wealth of information and examples of PowerShell scripts for AD management.
  4. Test Your Scripts: Always test your scripts in a controlled environment before deploying them in your production environment to avoid unintended consequences.

Help improve contributions

Contribution hidden for you

Insights from the community

Others also viewed

Explore topics

AMSI and PowerShell

PowerShell output of "amsiutils"

AMSI was created after PowerShell which means that earlier versions of PowerShell do not have the security features that AMSI provides. A common attack path for adversaries is to perform a “Downgrade attack” which effectively makes the process running PowerShell an exemption from the Antivirus solution.

Ever since AMSI was brought into the picture, multiple bypass methods have been developed. A deep dive of AMSI blogpost will come where we investigate the bits and bytes on how it works.

Install Active Directory PowerShell Module

  • Operating system: Windows Server is recommended for server installations, while Windows 10 or Windows 11 are suitable for client installations.
  • PowerShell version: Ensure that you have PowerShell 5.1 or later installed on your system.
  • Remote Server Administration Tools (RSAT): Depending on your Windows version, you may need to install RSAT, which includes the Active Directory module.
  • Internet access: Ensure that your system has internet access to download the module from the PowerShell Gallery. If your system is behind a proxy, you may need to configure proxy settings for PowerShell.
:/>  Лицензирование Windows. Установка и настройка KMS.

The steps required to install the Active Directory PowerShell Module vary slightly depending on your Windows operating system version, with additional pop-ups and confirmation dialogues present in some versions. 

These are the core steps:

  1. Open PowerShell as administrator
  2. Use Install-Module cmdlet:
  3. Confirm installation: Once the installation is complete, you may need to confirm that you want to install the module by typing ‘Y’ and pressing Enter.
  4. Check the execution policy

Day to day usage

PowerShell’s scripting capabilities and integration with various Microsoft and third-party technologies make it a valuable tool for not only IT professionals, but as well for people who want to cause you harm.

Next

Continuing the journey into the spider web of Active Directory, the next post is about something that we have touched upon already in this post, Domain Trust, and Access Control.

Active Directory: Introduction


What is the PowerShell Active Directory Module?

Simplifying Active Directory management

This automation not only reduces the likelihood of human error but also significantly speeds up the execution of repetitive tasks, as well as freeing up time for other duties.

Installing, importing, and loading modules

In PowerShell, understanding the distinction between installing, importing, and loading modules is crucial. 

  • Install-Module: This command is used to download and install a module from an online repository like the PowerShell Gallery. It’s typically used when you want to add a new module to your system.
  • Import-Module: Once a module is installed, the Import-Module cmdlet is used to make its cmdlets available for use in the current PowerShell session. This is necessary to execute the cmdlets and leverage the functionality of the module.
  • Load-Module: The Load-Module cmdlet is used to load a module into the current session’s memory, making its cmdlets available for use without importing. This approach is beneficial when you want to keep the module in memory for an extended period or when dealing with large modules to minimize loading times.

Import Active Directory PowerShell Module

Once the module is installed, it needs to be imported into your PowerShell session before you can start using its cmdlets. Importing loads the module into memory, making its functionality available for execution:

  1. Open PowerShell:
  2. Use Import-Module cmdlet
  3. Verify import: You can verify that the module has been successfully imported by running this simple cmdlet: Get-Command -Module RSAT-AD-PowerShell
:/>  Сменить рабочий диск

Loading the module efficiently

To ensure that the Active Directory module is loaded automatically when you open a PowerShell session, you can add the import command to your PowerShell profile script. This script runs every time you open a new PowerShell session:

  1. Check if a profile exists:

If the command returns False, you need to create a profile (step 2). If it returns True, proceed to step 3.

  1. Create a profile (if needed):
  2. Edit the profile script:
  3. Add Import-Module line:

PowerShell

The thing with PowerShell is that it is not an offensive security tool from the beginning, it was not intended to be at least. It is therefore important to restrict its usage, for example: does Alice from sales need PowerShell, or the capability to query Active Directory for a PowerShell session?

PowerView

PowerView is an offensive module that can be loaded to PowerShell that contains multiple scripts that makes it easier to navigate in the AD environment. This module has a plethora of capabilities.

Enumeration with PowerView

PowerView can provide several cmdlets (PowerShell commands) that help gather information about the Active Directory.

Here are some common ways to enumerate different components:

  1. Enumerates a domain’s users.

Picture of PowerShell output for Get-DomainUser -Domain windomain.local

  1. Enumerates users within the domain group” Help Desk Level 1”.

>Get-DomainGroup -Identity “Domain Guests”

Picture of PowerShell output for "Get-DomainGroup -Identity "Domain Guests"

Picture of PowerShell output for Get-ADUser -Filter *

C# Scripting

It is also possible to run C# code using PowerShell. This is since PowerShell is based on .NET and by extension can access all .NET libraries. Even though this expands the amazing capabilities of PowerShell, this also introduces security risks. By executing arbitrary C# code in PowerShell, it may introduce security risks if the code comes from an untrusted source. It could also enable an attacker that has gained access to the system to run C# code to execute malicious actions using common C# libraries to obfuscate themselves. Since this functionality is intended it can be harder to detect suspicious activity.

Other recommendations are:

  • Code Review and Analysis
  • Behavior Analysis
  • Monitoring and Logging
  • Whitelisting
  • Security Training
  • Security Policies

Оставьте комментарий