お知らせ: このページは現在英語のみで提供されています。日本語版は準備中です。ご不便をおかけして申し訳ございません。

Install the Active Directory Migration Agent

Refer to the following sections to prepare and install the Active Directory migration agent.

NOTE

The combined total of active Active Directory and Device migration agents in Fly should not exceed 5000. After a migration is complete, we recommend uninstalling the agents and removing them from Fly > Settings > Agents.

System Requirements

Refer to the following table for the system requirements of the Fly Active Directory Migration Agent.

ComponentsRequirements
Operating SystemWindows Server 2016, Windows Server 2019, Windows Server 2022, Windows 10, Windows 11*Note: 32-bit operating systems are not supported. Only operating systems with Desktop Experience are supported.
Number of CPU CoresRecommended: 4 or above.
Available Physical MemoryRecommended: 8 GB or above.
Available Disk SpaceRefer to Comment 1 below the table.
.NET Framework Version.NET Framework 4.7.2 to 4.8.
Net.Tcp Port Sharing ServiceNet.Tcp Port Sharing Service has started.
Transport Layer Security (TLS) VersionTLS 1.2 is enabled.
Visual C++ Redistributable VersionVisual C++ Redistributable 2015-2022.

Comment 1: The Agent server will store the temporary files and job logs of migrations.

  • We recommend 50 GB or above for migration projects with less than 100 GB of data.

  • We recommend 100 GB or above for large migration projects with more than 200 GB of data.

    When checking the installation rules, Fly checks the storage space of your drive C by default. Make sure there is available space of 2 GB or above in your drive C.

System Services Port Requirements

Refer to the following information for the system services port requirements of the Fly Active Directory Migration Agent.

Application ProtocolProtocolPorts
Lightweight Directory Access Protocol (LDAP) ServerTCP389
Remote Procedure Call (RPC)TCP135
RPC randomly allocated high TCP portsTCP49125 - 65535
Lightweight Directory Access Protocol over SSL (LDAPS) ServerTCP636
NOTE

If you are using port 389 for the connection, you can use the user principal name (UPN) for the service account. If you are using port 636 for the connection, a distinguished name (DN) is required for the service account.

For more details, refer to How to configure RPC dynamic port allocation to work with firewalls.

Network Requirements

Before performing Active Directory migrations in Fly, make sure the network of the server where you want to install the Active Directory agent can connect to the AvePoint Online Services, Fly, and the source/destination Active Directory.

If your organization has an access policy and only specific IP addresses are allowed, you need to navigate to AvePoint Online Services > Administration > Security > Reserved IP addresses to download the list of reserved IP addresses required by AvePoint Online Services and Fly, and then add the IP addresses to the safe IP address list of the server where you want to install the Active Directory agent.

Permission Requirements

Before performing Active Directory migrations in Fly, prepare the following accounts for the migration:

  • Local Administrator of the system where the agent will be installed is required by the installation.

  • Source Active Directory agent: A service account that is the domain admin of the source Active Directory.

    You can also prepare a user account with sufficient permissions instead of a domain admin by completing the following steps:

    1. Open Active Directory Users and Computers.

    2. Locate and right-click the domain name, and then click Properties.

    3. On the Security tab, click Add and select the user you want to assign permissions to.

    4. In the Permissions section, select Allow for the following permissions:

      • Add/remove replica in domain

      • Reanimate tombstones

      • Enable per user reversibly encrypted password

      • Manage replication topology

      • Add GUID

      • Read only replication secret synchronization

      • Run Protect Admin Groups Task

      • Write domain password & lockout policies

      • Write Other domain parameters (for use by SAM)

      • Migrate SID history

      • Unexpired password

      • Replicating Directory Changes

      • Replication synchronization

      • Replicating Directory Changes All

      • Update password not required bit

    5. Click the Advanced button. In the Advanced Security Settings window, select one of the permission entries, and click Edit.

    6. On the Permission Entry window, select the following permissions and properties:

      TypeEntries
      PermissionsList contents
      PermissionsRead all properties
      PermissionsWrite all properties
      PermissionsRead permissions
      PermissionsCreate all child objects
      PermissionsDelete all child objects
      PropertiesRead all properties
      PropertiesWrite all properties
    7. Once completed, click OK.

  • Destination Active Directory agent: If you want to use the default flymigrationExtensionAttribute attribute, a service account that is both a domain admin and a schema admin of the destination Active Directory is required.

    If you want to use custom attribute, a service account that is the domain admin of the destination Active Directory is required.

Download Agent

You can either download the Active Directory agent when creating a connection for Active Directory migration or follow the steps below to download the agent:

  1. Click Settings in the left pane, and select Agents > Active Directory agent tab.

  2. Click the down arrow next to Download agent, and then click Download source agent or Download destination agent to download the corresponding agent.

  3. In the panel, click Download.

  4. To verify whether a downloaded package has been tampered with, check its hash value and compare it with the one displayed in the panel. Following the steps below to obtain the hash value from the package:

    1. Extract the downloaded agent package.

    2. Open Windows PowerShell and enter the following commands:

      Get-FileHash -Algorithm SHA256 -Path "[file path]"

      Replace [file path] with the full path of the ZIP file in the extracted package.

      The ZIP file.

Install the Source Agent

Refer to the following steps to install the source Active Directory agent:

  1. Copy the downloaded ZIP file of the source agent to the machine where you want to install the agent.

  2. Extract the file.

  3. Right-click the Setup.exe application file in the extracted folder, and select Run as administrator.

  4. On the installation wizard, configure the installation path and click Next.

  5. Fly will perform a brief pre-scan of the environment to ensure that all rules meet the requirements. The status for each rule will be listed in the Status column.

    The Installation Rule Scanning window.

    For details about the system requirements, refer to System Requirements.

    NOTE

    You cannot proceed with the installation if any of the rules have a Status of Failed.

  6. Click Next to install the agent. When the installation is finished, click Configure now to configure settings for the agent.

    Installation succeed.

  7. In the Connect AvePoint Online Services step, configure the following settings:

    • AvePoint Online Services application (client) ID – Enter the ID of your app registration in AOS > Administration > App registrations. Note that the fly.admigration.readwrite.all permission is required for this app registration.

      Application (Client) ID.

    • Certificates – Enter the certificate thumbprint in AOS > Administration > App registrations. For how to upload a new certificate, refer to the Register an App section in Configure App Registrations for detailed information.

      Certificates.

    • Note the following:

      • Client secrets are not required for the connection.

      • The certificate (.pfx) must be installed on the Local Machine that has source Active Directory agent installed.

        Select Local Machine.

    • Proxy settings – Configure the following settings:

      • Proxy Host – The hostname or IP address of the proxy server.

      • Proxy Port – The port used to access the proxy server.

      • Username – The username to log in to the proxy server.

      • Password – The password to access the proxy server.

  8. Click Next to go to the Connect Connection step.

  9. In the Connect Connection step, configure the following settings:

    • Connection key – Paste the connection key you copied when you create the connection.

    • Connection name – After you entered the API key, the name of connection you created will be automatically filled in and cannot be edited.

    • Shared key – Enter 6 to 15 characters as the shared key. This key is used to encrypt Active Directory user passwords before sending them to the Fly database for migration. You need to save the shared key and provide the identical one to the destination agent for decryption.

    NOTE

    We recommend that you connect only one Active Directory agent per connection.

  10. Click Next to go to the Connect Active Directory step.

  11. In the Connect Active Directory step, configure the following settings:

    • Active Directory server information – Enter the host or IP: port of the source Active Directory.

      NOTE

      If you are using port 636 for the connection, a distinguished name (DN) is required for the service account. The SID migration may fail if port 389 is blocked by the source domain controller.

    • Domain – Click Connect to retrieve the domain name of the source Active Directory.

    • Service account – Enter the account of a domain admin of the source Active Directory.

    • Password – Enter the password for the account specified above.

    • Certificate Security – If you are using port 636 for the connection, select how to verify the Active Directory server certificate.

      • Use Certificate Authority (CA) – A Certificate Authority issues trusted certificates for the domain. Refer to Configure Server Certificate for details.

      • Allow self-signed certificates – Self-signed certificates trusted only on the local machine by default. Refer to Configure Server Certificate for details.

      • Validate with certificate thumbprint – Authenticates the connection by strictly matching the unique cryptographic thumbprint of the server certificate.

  12. Click Next to go to the Scan Source Objects step.

  13. In the Scan Source Objects step, select the OUs you want to scan. You can also enter the OU name in the search box to search for the OU.

  14. Click Next to go to the Scan Schedule step.

  15. In the Scan Schedule step, configure the following settings:

    • Scan security properties:

      • User passwords – Select this to scan and migrate the user passwords. Note that the Remote Procedure Call (RPC) server must be available for this migration.

      • Security Identifier (SID) History – Select this to scan and migrate the Security Identifier (SID) History. Note that the Remote Procedure Call (RPC) server must be available for this migration. Before performing the SID History migration, refer to the Prepare for SID History Migration section for detailed preparation steps.

    • Scan method:

      • Scan and send now – Select this to scan source objects and send the scanned objects to Fly immediately.

      • Scan on a specific date and time – Configure the start and end date and time, and the interval of recurring jobs.

  16. Click Submit to save your configurations.

NOTE

If the agent is installed on a domain controller machine, ensure you run the agent as an administrator.

Install the Destination Agent

Refer to the following steps to install the destination Active Directory agent:

  1. Copy the downloaded ZIP file of the destination agent to the machine where you want to install the agent.

  2. Extract the file.

  3. Right-click the Setup.exe application file in the extracted folder, and select Run as administrator.

  4. On the installation wizard, configure the installation path and click Next.

  5. Fly will perform a brief pre-scan of the environment to ensure that all rules meet the requirements. The status for each rule will be listed in the Status column.

    The Installation Rule Scanning window.

    For details about the system requirements, refer to System Requirements.

    NOTE

    You cannot proceed with the installation if any of the rules have a Status of Failed.

  6. Click Next to install the agent. When the installation is finished, click Configure now to configure settings for the agent.

    Installation succeed.

  7. In the Connect AvePoint Online Services step, configure the following settings:

    NOTE

    The same app registration can be used for both source and destination agents.

    • AvePoint Online Services application (client) ID – Enter the ID of your app registration in AOS > Administration > App registrations. Note that the fly.admigration.readwrite.all permission is required for this app registration.

      Application (Client) ID.

    • Certificates – Configure the certificate thumbprint in AOS > Administration > App registrations. For how to upload a new certificate, refer to the Register an App section in Configure App Registrations for detailed information.

      Certificates.

      Note the following:

      • Client secrets are not required for the connection.

      • The certificate (.pfx) must be installed on the Local Machine that has destination Active Directory agent installed.

      • You can choose to create a new certificate for the destination agent or use the same one as the source agent. In either case, the certificate (.pfx) must be installed on the Local machine that has destination Active Directory agent installed.

        Select Local Machine.

    • Proxy settings – Configure the following settings:

      • Proxy Host – The hostname or IP address of the proxy server.

      • Proxy Port – The port used to access the proxy server.

      • Username – The username to log in to the proxy server.

      • Password – The password to access the proxy server.

  8. Click Next to go to the Connect Connection step.

  9. In the Connect Connection step, configure the following settings:

    • Connection key – Paste the connection key you copied when you create the connection.

    • Connection name – After you entered the API key, the name of connection you created will be automatically filled in and cannot be edited.

    • Shared key – Enter the same shared key configured in the source agent. It is required to decrypt passwords while syncing the passwords for destination Active Directory users.

    NOTE

    We recommend that you connect only one Active Directory agent per connection.

  10. Click Next to go to the Connect Active Directory step.

  11. In the Connect Active Directory step, configure the following settings:

    • Active Directory server information – Enter the host or IP: port of the destination Active Directory.

      NOTE

      If you are using port 636 for the connection, a distinguished name (DN) is required for the service account. The SID migration may fail if port 389 is blocked by the source domain controller.

    • Domain – Click Connect to retrieve the domain name of the destination Active Directory.

    • Service account – Enter an account that is both a domain admin and a schema admin of the destination Active Directory.

    • Password – Enter the password for the account specified above.

    NOTE

    After the destination Active Directory is connected to Fly, a new attribute named flymigrationExtensionAttribute will be created in the destination Active Directory by default.

    To use your own custom attribute instead of the default flymigrationExtensionAttribute by completing the following steps:

    1. On the server where the agent is installed, navigate to...\FlyAdAgent\DestinationAgent\bin.

    2. Open the appsettins.json file.

    3. Add the following command:

      "EXTENSION_ATTRIBUTE_NAME": "<attribute name>" Replace "<attribute name>" with the name of your desired single-string attribute.

      Add your custom attribute.

    4. Once completed, save your updates. The configured attribute will be used for migration. We recommend you restart your Fly Destination AD Agent Service for the changes to take effect.

  12. Click Next to go to the Advanced settings step.

  13. In the Advanced settings step, you can turn on the toggle to enable the Security Identifier (SID) History migration if required. Note that before performing the SID History migration, refer to the Prepare for a SID History Migration section for detailed preparation steps.

  14. Once enabled, configure the following settings:

    • Source Active Directory server – Enter the host or IP: port of the source Active Directory.

    • Domain – Click Connect to retrieve the domain name of the source Active Directory.

    • Service account – Enter the account of a domain admin of the source Active Directory.

    • Password – Enter the password for the account specified above.

  15. Click Next to go to the Import Objects step.

  16. In the Import Objects step, configure the interval time for importing objects from Fly to the destination agent. The unit is Second.

  17. Click Finish to finish the installation of the destination agent.

NOTE

If the agent is installed on a domain controller machine, ensure you run the agent as an administrator.

Prepare for a SID History Migration

Before performing the Security Identifier (SID) History migration, you need to complete the following steps to prepare for the migration:

  1. Create a local group in the source domain:

    1. Open Active Directory Users and Computers.

    2. Locate and right-click the required OU and select New > Group.

    3. In the New Object - Group window, enter the group name using the following format: <source domain’s NetBIOS name>$$$.

      For example, if the NetBIOS name of your source domain is FLY, the group name must be FLY$$$.

      You can run the following commands in PowerShell to retrieve the BIOS name of your source domain: (Get-ADDomain).NetBIOSName.

      NOTE

      The SID History migration will fail if members are added to this newly created local group.

  2. Enable TCP/IP client support on the source domain PDC emulator:

    1. On the domain controller in the source domain that holds the PDC emulator operations master (also known as Flexible Single Master Operations or FSMO) role, navigate to Start menu> Run.

    2. In the Run window, enter regedit in the Open field, then click OK.

      Enter regedit.

    3. In the Registry Editor window, Go to the following registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\LSA

    4. Locate the TcpipClientSupport registry entry (type: REG_DWORD). Right-click it and select Modify....

    5. In the Edit DWORD (32-bit) Value window, enter 1 in the Value data field.

      Set Value data.

    6. Click OK.

    7. Close Registry Editor window and restart the computer for the change to take effect.

  3. Log on as an administrator to any domain controller in the destination and source domain.

  4. Navigate to Start menu > Administrative Tools > Group Policy Management.

  5. In the Group Policy Management window, navigate to Forest > Domains > Domain Name > Domain Controllers > Default Domain Controllers Policy.

  6. Right-click the Default Domain Controllers Policy, and click Edit. The Group Policy Management Editor window appears.

    NOTE

    If you cannot edit the policy, you can try to re-open the Group Policy Management Editor window by navigating to Start menu> Run. In the Run window, enter gpmc.msc in the Open field, then click OK.

    Open gpmc.msc.

  7. Enable auditing in the destination and source domain by following the steps below:

    1. In the Group Policy Management Editor window, navigate to Computer Configuration > Policies > Windows Settings > Security Settings > Local Policies > Audit Policy.

    2. In the right pane, configure the following audit policies:

      • Audit account management policy – Right-click it, and then click Properties. Select Define these policy settings, select both the Success and Failure checkboxes. Click Apply then OK.

      • Audit directory service access – Right-click it, and then click Properties. Select Define these policy settings, select the Success checkbox. Click Apply then OK.

    3. To apply the policy immediately, open an elevated Command Prompt and run the following command: gpupdate /force.

  8. Enable the advanced audit policy in the source and destination domain by following the steps below:

    1. In the Group Policy Management Editor window, navigate to Computer Configuration > Policies > Windows Settings > Security Settings > Advanced Audit Policy Configuration > Audit Policies > Account Management.

    2. In the right pane, configure the following policies by right-clicking each one and selecting Properties. Then click Configure, select both the Success and Failure checkboxes, and click Apply and then OK.

      • Audit Application Group Management

      • Audit Computer Account Management

      • Audit Distribution Group Management

      • Audit Other Account Management Events

      • Audit Security Group Management

      • Audit User Account Management

    3. In the Group Policy Management Editor window, navigate to Computer Configuration > Policies > Windows Settings > Security Settings > Advanced Audit Policy Configuration > Audit Policies > DS Access.

    4. In the right pane, configure the following policies by right-clicking each one and selecting Properties. Then click Configure, select the Success checkbox, and click Apply and then OK:

      • Audit Detailed Directory Service Replication

      • Audit Directory Service Access

      • Audit Directory Service Changes

      • Audit Directory Service Replication

    5. To apply the policy immediately, open an elevated Command Prompt and run the following command: gpupdate /force.

    NOTE

    You may also need to restart the domain controller for auditing to take effect. Even if the group policy for domain auditing is applied to the default domain controller, the server audit setting on the primary domain controller (PDC) may still be disabled. Confirm that this setting is enabled in the local security policy on the PDC. If it is not enabled, use the local security policy to enable it.

Set up Trust Between Domain Controllers

Refer to the following steps to set up trust between two domain controllers:

  1. Open the DNS Manager console on your local domain controller.

  2. In the left-hand navigation pane, locate and expand your active server node. Right-click directly on the Reverse Lookup Zones folder and select New Zone.

    Reverse Lookup Zones

  3. On the Welcome to the New Zone Wizard page, click Next to begin the configuration process.

  4. On the Zone Type page, select Primary zone and Store the zone in Active Directory, and then click Next.

    Zone Type

  5. On the Active Directory Zone Replication Scope page, select To all DNS servers running on domain controllers in this forest and then click Next.

    Active Directory Zone Replication Scope

  6. On the Reverse Lookup Zone Name page, select IPv4 Reverse Lookup Zone and then click Next.

    Reverse Lookup Zone Name

  7. Select Network ID, enter the IP address of your destination and then click Next.

    Network ID

  8. On the Dynamic Update page, select Allow both nonsecure and secure dynamic updates.

    Dynamic Update

  9. Click Next to finalize and then create the zone.

  10. After creating the reverse lookup zone, expand the Reverse Lookup Zones folder within the DNS Manager console and then click the specific network zone you created.

  11. Right-click in the empty space in the right-hand pane and then select New Pointer (PTR).

    Select New Pointer

  12. On the New Resource Record page, enter the IP address of the destination server in Host IP Address.

    New Resource Record

  13. Enter the domain name of the target server in Host name. You can also click Browse to locate the server record directly if it is already visible on the network. Then, click OK.

  14. In the left pane of DNS Manager, right-click the Conditional Forwarders folder and then select New Conditional Forwarder....

    Select New Conditional Forwarder

  15. On the New Conditional Forwarder page, enter the domain name of the destination domain in DNS Domain.

    New Conditional Forwarder

  16. Click Click here to add a... and add the IP address of the destination server.

  17. Select the checkbox of Store this conditional forwarder in Active Directory, and replicate it as follows: and select All DNS servers in this forest from the dropdown list. Then, click OK.

  18. Open the Active Directory Domains and Trusts management console, right-click your domain name in the left-hand navigation pane and then select Properties.

    Active Directory Domains and Trusts

  19. Click Trusts tab and then click New Trust....

    New Trust

  20. On the Trust Name page, enter the DNS Domain name in Name and then click Next.

    Trust name

  21. On the Trust Type page, select External trust and then click Next.

    Trust Type

  22. On the Direction of Trust page, select Two-way and then click Next.

    Direction of Trust

  23. On the Sides of Trust page, select Both this domain and the specified domain and then click Next.

    Sides of Trust

  24. On the User Name and Password page, enter a valid administrator username for the destination domain and the corresponding password, and then click Next.

    User Name and Password

  25. On the Outgoing Trust Authentication Level - Local Domain page, select Domain-wide authentication and then click Next.

    Outgoing Trust Authentication Level - Local Domain

  26. On the Confirm Outgoing Trust page, select Yes, confirm the outgoing trust and then click Next.

    Confirm Outgoing Trust

  27. On the Confirm Incoming Trust page, select Yes, confirm the incoming trust and then click Next to finalize the configuration.

    Confirm Incoming Trust

Account Permissions

To perform a SID History migration, specific permissions must be configured in both the source and target domains:

  • Migrate SID History permissions in the destination domain. This is typically granted to Domain Admins and Enterprise Admins by default.

  • To grant this permission to a specific user or group:

    1. Open Active Directory Users and Computers.

    2. Right-click your destination domain and select Properties.

    3. In the Properties window, click Security tab.

    4. Click Add to add required groups and users, or select an existing one to update.

    5. In the Permissions for Everyone section, select the Allow checkbox for Migrate SID history.

    6. Click Apply then OK.

  • Source credential’s administrator access to the source PDC emulator. This is typically granted to Domain Admins and Enterprise Admins by default.

  • To grant this permission to a specific user or group:

    1. Open Active Directory Users and Computers.

    2. Navigate to the Builtin container and double-click the Administrators group.

    3. On the Members tab, check if the source service account is a member of the group. If not, click Add to add the source service account.

    4. Click Apply then OK.

Configure Server Certificate

LDAP over SSL (LDAPS) requires a valid server certificate to be bound to the domain controller. Refer to the following approaches to configure a server certificate for the Active Directory secure port (LDAPS):

  • Certificate Authority (CA) – A Certificate Authority issues trusted certificates for the domain. Refer to the domain controller's position in the Active Directory forest, the following two types are available:

    • Enterprise CA – Recommended for production Root Domain Controllers.

    • Sub-domain CA (self-signed chain) – Required for sub-domain Domain Controllers.

      NOTE

      Enterprise CA on sub-domains is not supported by Microsoft.

  • Self-signed Certificate – Recommended for quick setup/lab environments — no CA required.

Certificate Authority (CA)

Root Domain Controllers

You can run the following command in Windows PowerShell to install and configure the Active Directory Certificate Services role:

Install-WindowsFeature -Name ADCS-Cert-Authority -IncludeManagementTools
Install-AdcsCertificationAuthority -CAType EnterpriseRootCA
NOTE

If an error occurs during the installation, please restart the Domain Controller and try again.

Sub-domain Domain Controllers

You can run the following command in Windows PowerShell to create a self-signed Root CA and uses it to issue a signed LDAPS certificate.

# ---- CONFIGURE CA FOR SUB DOMAIN ----
$newDomain = $env:USERDNSDOMAIN
if ([string]::IsNullOrWhiteSpace($newDomain)) {
    $newDomain = Read-Host "Enter DNS domain name (e.g. sub.domain.com)"
}

$newHostname = $env:COMPUTERNAME
if ([string]::IsNullOrWhiteSpace($newHostname)) {
    $newHostname = Read-Host "Enter hostname (e.g. DC01)"
}

$pfxPassword = Read-Host "Enter PFX export password" -AsSecureString

$exportPathInput = (Read-Host "Enter export folder path (default: C:\Certs)").Trim().TrimEnd('\')
if ([string]::IsNullOrWhiteSpace($exportPathInput)) { $exportPathInput = "C:\Certs" }

$exportPath    = Join-Path $exportPathInput "$newHostname-$newDomain.pfx"
$exportCerPath = Join-Path $exportPathInput "$newHostname-$newDomain.cer"
$rootCerPath   = Join-Path $exportPathInput "RootCA-$newDomain.cer"
$rootPfxPath   = Join-Path $exportPathInput "RootCA-$newDomain.pfx"
# ----------------------------------------------

$fqdn = "$newHostname.$newDomain"

$rootCASubject = ($newDomain -split '\.' | ForEach-Object { "DC=$_" }) -join ', '

$templateHex = "1e2000440065006f006d00610069006e0043006f006e00740072006f006c006c006500720"

New-Item -ItemType Directory -Force -Path "$exportPathInput" | Out-Null


# ============================================================
# STEP 1 Create Root CA
# ============================================================
Write-Host "`n[1/5] Creating Root CA..." -ForegroundColor Cyan

$rootCA = New-SelfSignedCertificate `
    -Subject $rootCASubject `
    -KeyLength 4096 `
    -HashAlgorithm SHA256 `
    -KeyUsage CertSign, CRLSign, DigitalSignature `
    -KeyExportPolicy Exportable `
    -NotAfter (Get-Date).AddYears(20) `
    -CertStoreLocation "Cert:\LocalMachine\My" `
    -TextExtension @("2.5.29.19={critical}{text}ca=TRUE&pathlength=1")

Write-Host "Root CA Thumbprint : $($rootCA.Thumbprint)"


# ============================================================
# STEP 2 Issue LDAPS Cert signed by Root CA
# ============================================================
Write-Host "`n[2/5] Issuing LDAPS certificate..." -ForegroundColor Cyan

$cert = New-SelfSignedCertificate `
    -Subject "CN=$fqdn" `
    -DnsName $fqdn, $newHostname, "localhost" `
    -KeyLength 2048 `
    -HashAlgorithm SHA256 `
    -KeyUsage DigitalSignature, KeyEncipherment `
    -TextExtension @(
        "2.5.29.37={text}1.3.6.1.5.5.7.3.1,1.3.6.1.5.5.7.3.2",
        "2.5.29.19={text}ca=FALSE"
    ) `
    -Signer $rootCA `
    -CertStoreLocation "Cert:\LocalMachine\My" `
    -KeyExportPolicy Exportable `
    -NotAfter (Get-Date).AddYears(5)

Write-Host "LDAPS Cert Thumbprint : $($cert.Thumbprint)"
Write-Host "Subject               : $($cert.Subject)"
Write-Host "DnsNameList           : $($cert.DnsNameList)"


# ============================================================
# STEP 3 Export all certs
# ============================================================
Write-Host "`n[3/5] Exporting certificates..." -ForegroundColor Cyan

Export-PfxCertificate `
    -Cert "Cert:\LocalMachine\My\$($rootCA.Thumbprint)" `
    -FilePath $rootPfxPath `
    -Password $pfxPassword
Export-Certificate `
    -Cert "Cert:\LocalMachine\My\$($rootCA.Thumbprint)" `
    -FilePath $rootCerPath -Type CERT

Export-PfxCertificate `
    -Cert "Cert:\LocalMachine\My\$($cert.Thumbprint)" `
    -FilePath $exportPath `
    -Password $pfxPassword
Export-Certificate `
    -Cert "Cert:\LocalMachine\My\$($cert.Thumbprint)" `
    -FilePath $exportCerPath -Type CERT

Write-Host "Root CA PFX : $rootPfxPath"
Write-Host "Root CA CER : $rootCerPath"
Write-Host "LDAPS PFX   : $exportPath"
Write-Host "LDAPS CER   : $exportCerPath"


# ============================================================
# STEP 4 Trust Root CA locally (DC + client machines need this)
# ============================================================
Write-Host "`n[4/5] Trusting Root CA..." -ForegroundColor Cyan

Import-Certificate -FilePath $rootCerPath `
    -CertStoreLocation "Cert:\LocalMachine\Root"
Import-Certificate -FilePath $rootCerPath `
    -CertStoreLocation "Cert:\CurrentUser\Root"

Write-Host "Root CA trusted in LocalMachine\Root and CurrentUser\Root"


# ============================================================
# STEP 5 Restart NTDS so DC picks up LDAPS cert
# ============================================================
Write-Host "`n[5/5] Restarting NTDS service..." -ForegroundColor Cyan

try {
    Restart-Service -Name "NTDS" -Force -ErrorAction Stop
    Write-Host "NTDS restarted successfully" -ForegroundColor Green
} catch {
    Write-Host "NTDS restart failed (may not be a DC yet): $_" -ForegroundColor Yellow
}


# ============================================================
# STEP 6 Verify LDAPS on port 636
# ============================================================
Write-Host "`nTesting LDAPS connection on port 636..." -ForegroundColor Cyan
Start-Sleep -Seconds 3

$tcp = New-Object System.Net.Sockets.TcpClient
try {
    $tcp.Connect($fqdn, 636)
    $stream    = $tcp.GetStream()
    $sslStream = New-Object System.Net.Security.SslStream($stream, $false, {
        param($s, $c, $ch, $e)
        Write-Host "  Cert Subject : $($c.Subject)"
        Write-Host "  Chain Errors : $e"
        return ($e -eq 'None')
    })
    $sslStream.AuthenticateAsClient($fqdn)
    Write-Host "LDAPS handshake SUCCESS on $fqdn`:636" -ForegroundColor Green
} catch {
    Write-Host "LDAPS test failed: $_" -ForegroundColor Red
    Write-Host "Ensure AD DS is installed and port 636 is open" -ForegroundColor Yellow
} finally {
    $tcp.Close()
}

Write-Host "`nDone. Distribute $rootCerPath to all client machines that need LDAPS access."

After running the command, copy RootCA-<domain>.cer to every client machine that needs LDAPS access and import it into Cert:\LocalMachine\Root.

Self-signed Certificate

For quick setup or lab environments where a CA is not available, you can run the following command in Windows PowerShell to create and configure a self-signed certificate:

# ---- CONFIGURE ----
$fqdn = $env:COMPUTERNAME + "." + $env:USERDNSDOMAIN
if ([string]::IsNullOrWhiteSpace($fqdn.Trim('.'))) {
    $fqdn = Read-Host "Enter FQDN (e.g. dc01.demoad.com)"
}

$pfxPassword = Read-Host "Enter PFX export password" -AsSecureString

$exportFolderInput = (Read-Host "Enter export folder path (default: C:\Certs)").Trim().TrimEnd('\')
if ([string]::IsNullOrWhiteSpace($exportFolderInput)) { $exportFolderInput = "C:\Certs" }

$exportPath    = Join-Path $exportFolderInput "$fqdn.pfx"
$exportCerPath = Join-Path $exportFolderInput "$fqdn.cer"

New-Item -ItemType Directory -Force -Path $exportFolderInput | Out-Null
# --------------------


# ============================================================
# STEP 1 Create self-signed certificate
# ============================================================
Write-Host "`n[1/5] Creating self-signed certificate for $fqdn..." -ForegroundColor Cyan

$cert = New-SelfSignedCertificate `
    -Subject "CN=$fqdn" `
    -DnsName $fqdn `
    -CertStoreLocation "Cert:\LocalMachine\My" `
    -KeyAlgorithm RSA `
    -KeyLength 2048 `
    -KeyUsage DigitalSignature, KeyEncipherment `
    -KeyExportPolicy Exportable `
    -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.1") `
    -Provider "Microsoft Software Key Storage Provider"

Write-Host "Thumbprint : $($cert.Thumbprint)"
Write-Host "Subject    : $($cert.Subject)"


# ============================================================
# STEP 2 Trust certificate in LocalMachine\Root
# ============================================================
Write-Host "`n[2/5] Adding certificate to Trusted Root store..." -ForegroundColor Cyan

$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("Root", "LocalMachine")
$store.Open("ReadWrite")
$store.Add($cert)
$store.Close()
Write-Host "Certificate added to Trusted Root" -ForegroundColor Green


# ============================================================
# STEP 3 Grant SYSTEM permissions to private key
# ============================================================
Write-Host "`n[3/5] Granting SYSTEM permissions to private key..." -ForegroundColor Cyan

$privateKey     = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert)
$keyName        = $privateKey.Key.UniqueName
$privateKeyPath = "$env:ProgramData\Microsoft\Crypto\Keys\$keyName"

$acl            = Get-Acl -Path $privateKeyPath
$systemRule     = New-Object System.Security.AccessControl.FileSystemAccessRule(
    "NT AUTHORITY\SYSTEM", "FullControl", "Allow"
)
$acl.AddAccessRule($systemRule)
Set-Acl -Path $privateKeyPath -AclObject $acl
Write-Host "SYSTEM permissions granted" -ForegroundColor Green

Get-Acl $privateKeyPath | Select-Object -ExpandProperty Access |
    Where-Object { $_.IdentityReference -like "*SYSTEM*" -or $_.IdentityReference -like "*NETWORK SERVICE*" }


# ============================================================
# STEP 4 Export certificate
# ============================================================
Write-Host "`n[4/5] Exporting certificate..." -ForegroundColor Cyan

Export-PfxCertificate `
    -Cert "Cert:\LocalMachine\My\$($cert.Thumbprint)" `
    -FilePath $exportPath `
    -Password $pfxPassword
Export-Certificate `
    -Cert "Cert:\LocalMachine\My\$($cert.Thumbprint)" `
    -FilePath $exportCerPath -Type CERT

Write-Host "PFX : $exportPath"
Write-Host "CER : $exportCerPath"


# ============================================================
# STEP 5 Restart NTDS and verify LDAPS
# ============================================================
Write-Host "`n[5/5] Restarting NTDS service..." -ForegroundColor Cyan

Restart-Service NTDS -Force
Start-Sleep -Seconds 15

$errorEvent = Get-WinEvent -LogName "Directory Service" -MaxEvents 5 | Where-Object { $_.Id -eq 1220 }
if ($errorEvent) {
    Write-Host "LDAPS still has issues - see events above" -ForegroundColor Red
    $errorEvent | Format-List TimeCreated, Message
} else {
    Write-Host "No LDAPS errors found - test your connection!" -ForegroundColor Green
}

Write-Host "`nTesting LDAPS connection on port 636..." -ForegroundColor Cyan
Start-Sleep -Seconds 3

$tcp = New-Object System.Net.Sockets.TcpClient
try {
    $tcp.Connect($fqdn, 636)
    $stream    = $tcp.GetStream()
    $sslStream = New-Object System.Net.Security.SslStream($stream, $false, {
        param($s, $c, $ch, $e)
        Write-Host "  Cert Subject : $($c.Subject)"
        Write-Host "  Chain Errors : $e"
        return ($e -eq 'None')
    })
    $sslStream.AuthenticateAsClient($fqdn)
    Write-Host "LDAPS handshake SUCCESS on $fqdn`:636" -ForegroundColor Green
} catch {
    Write-Host "LDAPS test failed: $_" -ForegroundColor Red
    Write-Host "Ensure AD DS is installed and port 636 is open" -ForegroundColor Yellow
} finally {
    $tcp.Close()
}

Write-Host "`nDone. CER file for distribution: $exportCerPath"

After running the command, import the .cer file into Cert:\LocalMachine\Root on each client machine to make clients trust the certificate.

NOTE

Client machines will show a certificate warning if you do not import the .cer file into their Trusted Root Certification Authorities store.