PowerShell Code: Find Active Directory Site Containing AD Subnet

Here’s a quick script that returns the site in the Active Directory forest given a subnet (ex. 10.20.30.0).

Match-Subnet2Site.ps1

 


Param
(
[string]$Subnet
)

$IPSubnetRegEx = '\b((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0)\b'
# $IPRegEx = '\b((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\b'

IF ($Subnet -match $IPSubnetRegEx)
{ Write-Output "Searching the AD forest for subnet: $Subnet " }
ELSE
{ Write-Error "The provided subnet ($Subnet) is not valid. Please enter as follows #.#.#.0 (ex. 10.22.33.0)" }

$ADForestName = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Name
$DomainDNS = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name

$ADSites = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites
$ADSites = $ADSites | sort-Object Name
[int]$ADSitesCount = $ADSites.Count
Write-output "Searching $ADSitesCount AD Sites in $ADForestName `r"

[string]$SearchResults = "Subnet $Subnet could not be found in the current Active Directory forest ($ADForestName)"
ForEach ($ADSitesItem in $ADSites)
{ ## OPEN ForEach ($ADSitesItem in $ADSites)
$ADSitesItemName = $ADSitesItem.Name
$ADSitesItemSubnetsCount = $ADSitesItem.Subnets.Count
IF ($ADSitesItem.Subnets.Count -gt 1)
{ ## OPEN IF ($ADSitesItem.Subnets.Count -gt 1)
$ADSitesItemSubnetsArray = $ADSitesItem.Subnets
Write-Verbose "The site $ADSitesItemName has $ADSitesItemSubnetsCount subnets "
ForEach ($ADSitesItemSubnetsItem in $ADSitesItemSubnetsArray)
{ ## OPEN ForEach ($ADSitesItemSubnetsItem in $ADSitesItemSubnets)
$ADSitesItemSubnets = $ADSitesItemSubnetsItem.Name
$ADSitesItemSubnetSite = $ADSitesItemSubnetsItem.Site
$ADSitesItemSubnetLocation = $ADSitesItemSubnetsItem.Location
Write-Verbose "Checking Site $ADSitesItemName subnet $ADSitesItemSubnets"
IF ($ADSitesItemSubnets -like "*$Subnet*")
{ [string]$SearchResults = "The subnet $Subnet is configured as part of the AD site $ADSitesItemName ($ADSitesItemSubnetLocation)" }
} ## CLOSE ForEach ($ADSitesItemSubnetsItem in $ADSitesItemSubnets)
} ## CLOSE IF ($ADSitesItem.Subnets.Count -gt 1)
ELSE
{ ## OPEN ELSE ($ADSitesItem.Subnets.Count -lt 1)
$ADSitesItemSubnets = $ADSitesItem.Subnets[0].Name
$ADSitesItemSubnetSite = $ADSitesItem.Subnets[0].Site
$ADSitesItemSubnetLocation = $ADSitesItem.Subnets[0].Location

Write-Verbose "Checking Site $ADSitesItemName single subnet $ADSitesItemSubnets"
IF ($ADSitesItemSubnets -like "*$Subnet*")
{ [string]$SearchResults = "The subnet $Subnet is configured as part of the AD site $ADSitesItemName ($ADSitesItemSubnetLocation)" }
} ## CLOSE ELSE ($ADSitesItem.Subnets.Count -lt 1)

[array]$ADSitesItemSubnetsArray = $ADSitesItemSubnets -Split(", ")

} ## CLOSE ForEach ($ADSitesItem in $ADSites)

return $SearchResults

Azure Active Directory Stats

 

  • Over 2.9 Million Organizations are using Azure Active Directory
  • More than 10 Billion Authentications per week
  • Azure Active Directory is spread out across 14 data centers
  • Contains more than 240 million user accounts
  • Organizations using Azure Active Directory across 127 countries
  • Supports over 1400 integrated third-party apps

Azure AD Statistics

LOL! Lingering Object Liquidator for Active Directory

Microsoft released the LOL GUI tool for removing Active Directory lingering objects. Historically, removing lingering objects from AD had been a painful process.

Note that LOL is not a straightforward download. Follow the following steps to download:

  1. Log on to the Microsoft Connect site (using the Sign in) link with a Microsoft account:: http://connect.microsoft.com
    Note: You may have to create a profile on the site if you have never participated in Connect.
  2. Open the Non-feedback Product Directory:
    https://connect.microsoft.com/directory/non-feedback
  3. Join the following program:
    AD Health
    Product Azure Active Directory Connection Join link
  4. Click the Downloads link to see a list of downloads or this link to go directly to the Lingering Objects Liquidator download. (Note: the direct link may become invalid as the tool gets updated.)
  5. Download all associated files
  6. Double click on the downloaded executable to open the tool.

 

Why you should care about lingering object removal

Widely known as the gift that keeps on giving, it is important to remove lingering objects for the following reasons

  • Lingering objects can result in a long term divergence for objects and attributes residing on different DCs in your Active Directory forest
  • The presence of lingering objects prevents the replication of newer creates, deletes and modifications to destination DCs configured to use strict replication consistency. These un-replicated changes may apply to objects or attributes on users, computers, groups, group membership or ACLS.
  • Objects intentionally deleted by admins or application continue to exist as live objects on DCs that have yet to inbound replicate knowledge of the deletes.

Lingering Object Liquidator automates the discovery and removal of lingering objects by using the DRSReplicaVerifyObjects method used by repadmin /removelingeringobjects and repldiag combined with the removeLingeringObject rootDSE primitive used by LDP.EXE. Tool features include:

  • Combines both discovery and removal of lingering objects in one interface
  • Is available via the Microsoft Connect site
  • The version of the tool at the Microsoft Connect site is an early beta build and does not have the fit and finish of a finished product
  • Feature improvements beyond what you see in this version are under consideration

 

 

From Microsoft KB 910205:

Lingering objects can occur if a domain controller does not replicate for an interval of time that is longer than the tombstone lifetime (TSL). The domain controller then reconnects to the replication topology. Objects that are deleted from the Active Directory directory service when the domain controller is offline can remain on the domain controller as lingering objects. This article contains detailed information about the events that indicate the presence of lingering objects, the causes of lingering objects, and the methods that you can use to remove lingering objects.

 

Tombstone lifetime and replication of deletions

When an object is deleted, Active Directory replicates the deletion as a tombstone object. A tombstone object consists of a small subset of the attributes of the deleted object. By inbound-replicating this object, other domain controllers in the domain and in the forest receive information about the deletion. The tombstone is retained in Active Directory for a specified period. This specified period is called the TSL. At the end of the TSL, the tombstone object is permanently deleted.

The default value of the TSL depends on the version of the operating system that is running on the first domain controller that is installed in a forest. The following table indicates the default TSL values for different Windows operating systems.

First domain controller in forest root Default tombstone lifetime
Windows 2000 60 days
Windows Server 2003 60 days
Windows Server 2003 with Service Pack 1 180 days

Note The existing TSL value does not change when a domain controller is upgraded to Windows Server 2003 with Service Pack 1 (SP1). The existing TSL value is maintained until you manually change it.

After the tombstone is permanently deleted, the object deletion can no longer be replicated. The TSL defines how long domain controllers in the forest retain information about a deleted object. The TSL also defines the time during which all direct and transitive replication partners of the originating domain controller must receive a unique deletion.

How lingering objects occur

When a domain controller is disconnected for a period that is longer than the TSL, one or more objects that are deleted from Active Directory on all other domain controllers may remain on the disconnected domain controller. Such objects are called lingering objects. Because the domain controller is offline during the time that the tombstone is alive, the domain controller never receives replication of the tombstone.

When this domain controller is reconnected to the replication topology, it acts as a source replication partner that has an object that its destination partner does not have.

Replication problems occur when the object on the source domain controller is updated. In this case, when the destination partner tries to inbound-replicate the update, the destination domain controller responds in one of two ways:

  • If the destination domain controller has Strict Replication Consistency enabled, the controller recognizes that it cannot update the object. The controller locally stops inbound replication of the directory partition from the source domain controller.
  • If the destination domain controller has Strict Replication Consistency disabled, the controller requests the full replica of the updated object. In this case, the object is reintroduced into the directory.

Causes of long disconnections

The following conditions can cause long disconnections:

  • A domain controller is disconnected from the network and is put in storage.
  • The shipment of a pre-staged domain controller to its remote location takes longer than a TSL.
  • Wide area network (WAN) connections are unavailable for long periods. For example, a domain controller onboard a cruise ship may be unable to replicate because the ship is at sea for longer than the TSL.
  • The reported event is a false positive because an administrator shortened the TSL to force the garbage collection of deleted objects.
  • The reported event is a false positive because the system clock on the source or on the destination domain controller is incorrectly advanced or rolled back. Clock skews are most common following a system restart. Clock skews may occur for the following reasons:
    • There is a problem with the system clock battery or with the motherboard.
    • The time source for a computer is configured incorrectly. This includes a time source server that is configured by using Windows Time service (W32Time), by using a third-party time server, or by using network routers.
    • An administrator advances or rolls back the system clock to extend the useful life of a system state backup or to accelerate the garbage collection of deleted objects. Make sure that the system clock reflects the actual time. Also, make sure that event logs do not contain invalid events from the future or from the past.

Removing lingering objects from the forest

Windows 2000-based forests

For more information about how to remove lingering objects in a Windows 2000-based domain, click the following article number to view the article in the Microsoft Knowledge Base:

314282 Lingering objects may remain after you bring an out-of-date global catalog server back online

Windows Server 2003-based forests

For information about how to remove lingering objects from Windows Server 2003-based forests, visit the following Microsoft Web site:

For more information, click the following article number to view the article in the Microsoft Knowledge Base:

892777 Windows Server 2003 Service Pack 1 Support Tools

Preventing lingering objects

The following are methods that you can use to prevent lingering objects.

Method 1: Enable the Strict Replication Consistency registry entry

You can enable the Strict Replication Consistency registry entry so that suspect objects are quarantined. Then, administrations can remove these objects before they spread throughout the forest.

If a writable lingering object is located in your environment, and an attempt is made to update the object, the value in the Strict Replication Consistency registry entry determines whether replication proceeds or is stopped. The Strict Replication Consistency registry entry is located in the following registry subkey:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NTDS\Parameters

The data type for this entry is REG_DWORD. If you set the value to 1, the entry is enabled. Inbound replication of the specified directory partition from the source is stopped on the destination. If you set the value to 0, the entry is disabled. The destination requests the full object from the source domain controller. The lingering object is revived in the directory as a new object.

The default value for the Strict Replication Consistency registry entry is determined by the conditions under which the domain controller was installed in the forest.

Note Raising the functional level of the domain or the forest does not change the replication consistency setting on any domain controller.

By default, the value of the Strict Replication Consistency registry entry on domain controllers that are installed in a forest is 1 (enabled) if the following conditions are true:

  • The Windows Server 2003 version of Winnt32.exe is used to upgrade a Windows NT 4.0 primary domain controller (PDC) to Windows Server 2003. This computer creates the forest root domain of a new forest.
  • Active Directory is installed on a server that is running Windows Server 2003. This computer creates the forest root domain of a new forest.

By default, the value of the Strict Replication Consistency registry entry on domain controllers is 0 (disabled) if the following conditions are true:

  • A Windows 2000-based domain controller is upgraded to Windows Server 2003.
  • Active Directory is installed on a Windows Server 2003-based member server in a Windows 2000-based forest.

If you have a domain controller that is running Windows Server 2003 with SP1, you do not have to modify the registry to set the value of the Strict Replication Consistency registry entry. Instead, you can use the Repadmin.exe tool to set this value for one domain controller in the forest or for all the domain controllers in the forest.

For more information about how to use Repadmin.exe to set Strict Replication Consistency, visit the following Microsoft Web site:

Method 2: Monitor replication by using a command-line command

To monitor replication by using the repadmin /showrepl command, follow these steps:

  1. Click Start, click Run, type cmd, and then click OK.
  2. Type repadmin /showrepl * /csv >showrepl.csv, and then press ENTER.
  3. In Microsoft Excel, open the Showrepl.csv file.
  4. Select the A + RPC column and the SMTP column.
  5. On the Edit menu, click Delete.
  6. Select the row that is immediately under the column headers.
  7. On the Windows menu, click Freeze Pane.
  8. Select the complete spreadsheet.
  9. On the Data menu, point to Filter, and then click Auto-Filter.
  10. On the heading of the Last Success column, click the down arrow, and then click Sort Ascending.
  11. On the heading of the src DC column, click the down arrow, and then click Custom.
  12. In the Custom AutoFilter dialog box, click does not contain.
  13. In the box to the right of does not contain, type del.

    Note This step prevents deleted domain controllers from appearing in the results.

  14. On the heading of the Last Failure column, click the down arrow, and then click Custom.
  15. In the Custom AutoFilter dialog box, click does not equal.
  16. In the box to the right of does not equal, type 0.
  17. Resolve the replication failures that are displayed.

 

PowerShell Code: Active Directory Domain Controller Discovery

There are several different ways to find AD Domain Controllers (DCs).

Here are a few:

AD PowerShell Module: Discover the closest Domain Controller running the AD web services (support PowerShell AD cmdlets):

import-module activedirectory
Get-ADDomainController -discover -forcediscover -nextclosestsite -service ADWS

  • discover – find a DC
  • forcediscover – re-discover a DC and not use a cached DC
  • nextclosestsite – if there is no DC discovered in the local site, use the AD topology to find the closest DC in another site.
  • service – the DC must support these services.


AD PowerShell Module: Discover all Domain Controller in the domain:

import-module activedirectory
Get-ADDomainController -filter *

  • filter * – find all Domain Controllers


Discover all Domain Controller in the domain using ADSI:

[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers

 

Discover all Global Catalogs in the forest using ADSI:

[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GlobalCatalogs

 

You can also use the Active Directory cmdlets to get computer information about Domain Controllers:

import-module activedirectory
get-ADComputer -filter { PrimaryGroupID -eq “516” } -properties PrimaryGroupID

 

 

 

Powershell Filter Operators

Once you get used to Powershell, you will want to do more and more with it.  One of the keys to leveraging the power of PowerShell is filters.
PowerShell commandlets all support filters (well, most of them anyway).  This means you can drill down to resulting data subsets.
If you run into commandlets that don’t support the native -filter you can always pipe to where-object (aka “where”).

In other words you can do this: get-service | Where {$_.Status -eq “Running”}
This takes the results of a generic get-service request which returns a full list of system services and pares it down to only the running services.
Change “Running” to “Stopped” and you get, obviously a list of services that are stopped.

You can also pipe the service name into the get-service commandlet: “W32Time” | get-service

Here’s a great chart I found on the MSDN Blogs that describes what each filter operator does:

Logical Operator Description Equivalent LDAP operator/expression
-eq Equal to. This will not support wild card search. =
-ne Not equal to. This will not support wild card search. ! x = y
-like Similar to -eq and supports wildcard comparison. The only wildcard character supported is: * =
-notlike Not like. Supports wild card comparison. ! x = y
-approx Approximately equal to ~=
-le Lexicographically less than or equal to <=
-lt Lexicographically less than ! x >= y
-ge Lexicographically greater than or equal to >=
-gt Lexicographically greater than ! x <= y
-and AND &
-or OR |
-not NOT !
-bor Bitwise OR :1.2.840.113556.1.4.804:=
-band Bitwise AND :1.2.840.113556.1.4.803:=
-recursivematch Uses LDAP_MATCHING_RULE_IN_CHAIN (Win2k3 SP2 and above) :1.2.840.113556.1.4.1941:=

Using filters is extremely helpful is narrowing down the scope to fine-tune the data you need to work with and this chart is one I frequently reference.

PowerShell: Parse a Large Multi-Line Text Field Based on String Value & Extract Text

Parsing a large multi-line text field (variable) for a specific string and extract text from it:

$EventMessage =
@”
An account was successfully logged on.

Subject:
Security ID:  SYSTEM
Account Name:  METCORPWKS201$
Account Domain:  METCORP
Logon ID:  0x2b5
Logon Type:10
New Logon:
Security ID:  METCORP\Administrator
Account Name:  Administrator
Account Domain:  METCORPWKS201
Logon ID:  0bc123d
Logon GUID:  {00000000-0000-0000-0000-000000000000}
Process Information:
Process ID:  0x123
Process Name:  C:\Windows\System32\winlogon.exe
Network Information:
Workstation Name: METCORPWKS201
Source Network Address: 10.10.10.201
Source Port:  1234
Detailed Authentication Information:
Logon Process:  User32
Authentication Package: Negotiate
Transited Services: –
Package Name (NTLM only): –
Key Length:  0

This event is generated when a logon session is created. It is generated on the computer that was accessed.

The subject fields indicate the account on the local system which requested the logon. This is most commonly a service such as the Server service, or a local process such as Winlogon.exe or Services.exe.

The logon type field indicates the kind of logon that occurred. The most common types are 2 (interactive) and 3 (network).

The New Logon fields indicate the account for whom the new logon was created, i.e. the account that was logged on.

The network fields indicate where a remote logon request originated. Workstation name is not always available and may be left blank in some cases.

The authentication information fields provide detailed information about this specific logon request.

The authentication information fields provide detailed information about this specific logon request.

Logon GUID is a unique identifier that can be used to correlate this event with a KDC event.
Transited services indicate which intermediate services have participated in this logon request.
Package name indicates which sub-protocol was used among the NTLM protocols.
Key length indicates the length of the generated session key. This will be 0 if no session key was requested.

“@

$EventMessageLogonNumber = $EventMessage | Select-String -Pattern “Logon Type:\w+” -AllMatches | Select -ExpandProperty matches | Select -ExpandProperty value
$EventMessageAccountNameText = $EventMessage | Select-String -Pattern “Account Name:\s+\w+” -AllMatches | Select -ExpandProperty matches | Select -ExpandProperty value
$EventMessageAccountName = (($EventMessageNameText -split “:”)[1]) -Replace(“`t”,””)
$EventMessageWorkstationNameText = $EventMessage | Select-String -Pattern “Workstation Name:\s+\S+” -AllMatches | Select -ExpandProperty matches | Select -ExpandProperty value
$EventMessageWorkstationName = (($EventMessageWorkstationNameText -split “:”)[1]) -Replace(“`t”,””)
$EventMessageSourceIPText = $EventMessage | Select-String -Pattern “Source Network Address:\s+\S+” -AllMatches | Select -ExpandProperty matches | Select -ExpandProperty value
$EventMessageSourceIP = (($EventMessageSourceIPText -split “:”)[1]) -Replace(“`t”,””)
$EventMessageLogonNumber
$EventMessageAccountName
$EventMessageWorkstationName
$EventMessageSourceIP

Read-Only Domain Controller (RODC) Information

The RODC is one of the most interesting new features of Windows Server 2008.

RODCs provide the following:

  • Read-only Active Directory Database – Read-only copy of Active Directory provides a more secure option for distant locations such as a branch office. Changes attempted against the RODC are referred to the next upstream DC.
  • Read-only DNS Server – DNS on the RODC can be configured as a DNS Secondary of the Active Directory Integrated DNS zone file or of a Primary standard DNS zone.
  • Credential Caching – By default, no passwords are stored on a RODC (including computer passwords), though specific groups can be configured for password caching.  Physical attacks on Active Directory stored domain credentials on RODCs are not possible when password caching is disabled.
  • Administrator Role Separation – Administration of a RODC can be delegated to a domain user account without providing “keys to the kingdom” access or significantly decreasing the security posture of Active Directory.
  • Reduced Exposure – Filtering specific object attributes to ensure they don’t exist on RODCs.  For example, there may be attributes that were added after the instantiation of Active Directory such as specific attributes that are confidential (SSNs, clearance, etc).
  • Unidirectional Replication – The only replication that occurs on a RODC is inbound replication from a fully writable 2008 DC.  This reduces the amount of replication traffic that occurs in the environment as well as the number of connections and connection objects at the primary site.  This also protects the rest of the directory from memory corruption of the database due to hardware failure or improper shutdown.
  • SYSVOL Modification Isolation – If SYSVOL is modified on a RODC in the field, the change stays on the RODC and is not replicated out.  This includes added, deleted, and modified SYSVOL files.

There are several key differences between a writable DC and a RODC.
These differences include the following:

  • Active Directory Database – DCs host the only writable copies of the Active Directory database and therefore can perform read and write operations against the directory database. RODCs host read-only copies of the AD database which do not include security principal secrets (passwords).  Since RODCs are unable to perform write operations on the RODC hosted AD database, some write operations are forwarded to full DCs and other times the RODC provides referrals to clients  in order for the client to locate a writable DC.
  • Active Directory Replication – Writable DCs replicate among themselves frequently and as needed to ensure directory consistency. RODCs never replicate to or from another RODC. RODCs also never send replication data to other DCs. RODCs can only receive replication from a 2008 writable DC.  This replication method is the same for replicating SYSVOL.
  • Local AD database storage – Writable DCs host a full copy of the Active Directory database including security principal credentials.  RODCS host a copy of the database except for attributes that are part of the RODC Filtered Attribute Set (FAS) and security principal credentials. Specific credentials can be identified and selected for password replication to the RODC.
  • Administration – Writable DC are administered by the domain Administrators and Domain Admins groups; however, membership in these groups also grants enhanced Active Directory rights. RODCs provide the capability to delegate a standard user account and/or user group full administrative rights to the RODC without providing elevated Active Directory permissions.

When placing a RODC at a site, there are several important considerations:

  1. Think twice about placing a RODC in the same site as a DC.  RODCs are meant to be used where there are security and/or other concerns (delegation, replication, etc).  If a writable DC is in the site, it makes more sense to place another DC there instead of a RODC.
  2. If a location requires a DC that hosts additional services (roles), the DC placed at the site should be a RODC.  DCs should not host services beyond core Active Directory services.
  3. There must be a 2008 (or newer) DC upstream from the RODC to enable proper replication. It is best to have two 2008 (or newer) DCs nearby to enable efficient replication.
  4. All of the users located at the site serviced by a RODC should be members of a site group which is added to the password policy for the RODC.  This will ensure the user passwords are cached for logon in the event the network connection to a nearby writable DC is down.
  5. All of the computers (workstations & servers) located at the site serviced by a RODC should be members of a site group which is added to the password policy for the RODC.  This will ensure the computer passwords are cached ensuring proper computer operation in the event the network connection to a nearby writable DC is down.
  6. RODCs never communicate with other RODCs.  This means if there are multiple RODCs in the same site, they may have different accounts cached and possibly different password policies. This scenario is why it may not make sense to place two RODCs in a site.

Note: If items 3 & 4 are not configured to enable password caching, a writable DC must be available to service authentication (Kerberos) requests; both the computer & user passwords must be cached in order for a Kerberos ticket to be granted.

Here are some excellent RODC resources:

Active Directory Pentest Recon Part 1: SPN Scanning aka Mining Kerberos Service Principal Names

I wrote a lengthy post on Kerberos earlier which describes the Kerberos protocol as well as how Active Directory leverages Kerberos.

There are several interesting Active Directory components useful to the pentester. The one I cover here relates to how Kerberos works, specifically Service Principal Names. As I mentioned in my Kerberos post, Service Principal Names (aka SPNs) are effectively the sign posts of Kerberos pointing users where to go to connect to resources. I won’t deal with Kerberos in depth here, but will recap.

Kerberos in a nutshell:

  1. When a user logs on to Active Directory, the user authenticates to the Domain Controller (DC) using the user’s password which of course the DC knows.
  2. The DC sends the user a Ticket Granting Ticket (TGT) Kerberos ticket. The TGT is presented to any DC to prove authentication for Kerberos service tickets.
  3. The user opens up Outlook which causes the user’s workstation to lookup the Service Principal Name (SPN) for the user’s Exchange server.
  4. Once the SPN is identified, the computer communicates with a DC again and presents the user’s TGT as well as the SPN for the resource to which the user needs to communicate.
  5. The DC replies with the Ticket Granting Service (TGS) Kerberos service ticket.
  6. The user’s workstation presents the TGS to the Exchange server for access.
  7. Outlook connects successfully.

Obviously this is an over-simplification, but explains why the SPN is important.
The key take-away here is that every service that is enabled for Kerberos authentication must have a SPN.

You may be thinking: “Ok, got it. So, what’s the point?”

This is where things get interesting.

Since every server needs to register SPNs for Kerberos authenticated services, this provides a perfect method for gathering information about an environment without port-scanning.

For example:

  • An administrator installs and configures Microsoft SQL Server on a server called “MetcorpKCS17” with a SQL instance listening on port 3170 3 & 3171.

The SPNs created by this action look like this:
MSSQLSvc/MetcorpKCS17.adsecurity.org:3170
MSSQLSvc/MetcorpKCS17.adsecurity.org:3171

The part in blue is the service component followed by a slash, the part in orange is the computer’s FQDN followed by a colon, and the last part in green is the network port number (or instance or some other unique identifier for this service on the server). Interestingly enough, the number at the end doesn’t have to be the port the service is listening on the server since Kerberos matches the SPN request to an existing SPN in the directory. With that stated, most of the time with few exceptions (as in practically none), the port noted in the SPN is the listening port on the server. Not all SPNs include a port.

Historically identifying that SQL is running on this server would either require a port scan of all ports on each server to find the non-standard ports or perform a “SQL ping” to UDP 1434 which would respond with the SQL instances and ports as well as the SQL version(s). Port scans on an internal network are typically noisy and the “SQL ping” approach to server profiling is usually flagged by IDS/IPS.

Now we have a better method for discovering SQL servers in an Active Directory domain or forest: perform a search of AD for ServicePrincipalName=MSSQL*
I used this method over the past couple of years for helping customers identify SQL servers in their environment to secure or decomission (saving licensing money).

While doing research on the different SPN types in Active Directory environments, I found there wasn’t much information on different SPNs and what they are used for – at least not in one place. So, I added created a Service Principal Name reference page listing all of the SPNs I have discovered.

There are several interesting services that leverage SPNs for Kerberos Auth which can be discovered with simple AD searches:

  • exchange*
  • http
  • ldap
  • nfs
  • *sql*
  • wsman

Interestingly enough, SPNs are queried almost constantly in an Active Directory environment all the time as clients request access to services. Furthermore, since the servicePrincipalName attribute is indexed in Active Directory, the results are usually returned in under a second.

Here’s the PowerShell (v2) code for discovering all SQL servers in the Active Directory forest:

ADForestInfoRootDomain = ([System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()).RootDomain

$ADForestInfoRootDomainDN = “DC=” + $ADForestInfoRootDomain -Replace(“\.”,’,DC=’)

$ADDomainInfoLGCDN = ‘GC://’ + $ADForestInfoRootDomainDN

$root = [ADSI]$ADDomainInfoLGCDN

$ADSPNSearcher = new-Object System.DirectoryServices.DirectorySearcher($root,”(serviceprincipalname=*sql*)”)

$ADSPNSearcher.PageSize = 500

$AllADSQLServerSPNs = $ADSPNSearcher.FindAll()

 

Note: This PowerShell code can be run as a standard AD user.
Change the bolded text to change the service type.

In order to simplify the identification of SQL servers and Exchange Servers (and others) in your Active Directory environment, I wrote PowerShell functions supporting this. These are available in GitHub: https://github.com/PyroTek3/PowerShell-AD-Recon

There’s a ton more information on what Service Principal Names are, and what they do, etc can be found on the TechNet Wiki.

 

Kerberos, Active Directory’s Secret Decoder Ring

Kerberos Overview

Kerberos is a protocol with roots in MIT named after the three-headed dog, Cerberus. Named because there are 3 parties: the client, the resource server, and a 3rd party (the Key Distribution Center, KDC).

Kerberos can be a difficult authentication protocol to describe, so I will attempt to simplify it as best as possible.

Kerberos authentication leverages long-term asymmetric keys (public key) and short-term symmetric keys (session keys).

Asymmetric key cryptography uses two mathematically connected keys where one key is used to encrypt and the other is used to decrypt data. This is most commonly used in Public Key encryption (PKI) where one of the keys is kept secret by the user or service (Private Key) and the other key is available to anyone who wants it (Public Key). In this manner a user can sign (encrypt a hash with the private key) data to ensure it originated from that user without modification (the receiver decrypts the hash with the public key). Also a person can use the user’s public key to encrypt data so that only the user can decrypt it with the user’s private key.

Symmetric key cryptography uses one key to encrypt and the same to decrypt the data. This is also referred to as a shared secret.

Since asymmetric key cryptography is more processor intensive, it is typically only used to encrypt session keys which use symmetric keys (shared secret).

Active Directory implements Kerberos version 5 in two components: the Authentication service and the Ticket-granting service.

The Authentication Service (AS) is the first contact the client has with Kerberos and is used to lookup the user’s password and create the Ticket Granting Ticket (TGT). The AS also creates the session key the user will use for future communication with Kerberos.

The Ticket Granting Ticket (TGT) is the Kerberos ticket for the Ticket Granting Service (runs on the KDC) and is encrypted using the KDC key (KRBTGT domain Kerberos account), meaning that only a KDC can decrypt and read the ticket. While the user’s ticket ,the TGT, is set to expire after 10 hours (AD default), it can be renewed as often as needed during the TGT renewable lifetime which is 7 days (AD default). Once the authenticating user has a TGT, it presents the TGT to the KDC to get a Service Ticket for the Ticket Granting Service (TGS) on the KDC. Most key Kerberos communication occurs over UDP port 88, though starting with Windows Vista & Windows Server 2008 now default to using TCP for Kerberos ticket requests.

There is a myth in the Windows Kerberos world that if a workstation’s clock is skewed more than 5 minutes from that of the Domain Controller, Kerberos authentication wouldn’t work.
Technically, all clocks in the Kerberos world must be kept closely in-sync to prevent replay attacks. By default, Microsoft Active Directory has a tolerance of 5 minutes. Though in most cases, this doesn’t mater. When a client sends a Kerberos request to a DC, the DC will reply with a “KRB_ERROR – KRB_AP_ERR_SKEW (37)” and the Windows client will update its time for the Kerberos session with the DC and resend the request. Provided the clock skew between the client and DC is not more than the ticket lifetime (10 hours by default), the second request will be successful.

Kerberized Internet Negotiation of Keys (KINK) RFC 4430 details how this works:

If the server clock and the client clock are off by more than the policy-determined clock skew limit (usually 5 minutes), the server MUST return a KRB_AP_ERR_SKEW.  The optional client’s time in the KRB-ERROR SHOULD be filled out.  If the server protects the error by adding the Cksum field and returning the correct client’s time, the client SHOULD compute the difference (in seconds) between the two clocks based upon the client and server time contained in the KRB-ERROR message.  The client SHOULD store this clock difference and use it to adjust its clock in subsequent messages.  If the error is not protected, the client MUST NOT use the difference to adjust subsequent messages, because doing so would allow an attacker to construct authenticators that can be used to mount replay attacks.

KB956627 also describes this behavior.
Confused yet?
Keep reading, it gets easier…

Every service that is Kerberos enabled has an entry point called a Service Principal Name (SPN) and each Kerberos user has a User Principal Name (UPN). For example, a user named Joe User in the ADSECURITY.ORG Kerberos realm aka AD domain (the Kerberos realm is always all Caps) has a UPN of JoeUser@ADSecurity.org. If Joe User initiates a connection to the share path \\server1.ADSecurity.org\Shared then Joe’s workstation will lookup the computer server1.ADSecurity.org in Active Directory and read its SPN attribute (cifs/server1.ADSecurity.org). The computer SPN is used to identify the application server in the Kerberos TGS ticket request. Furthermore, when Joe opens Outlook, his workstation performs similar actions looking up the Exchange server’s SPN.
Exchange 2010 has a number of registered SPNs; here are a few of them used as part of a client connection (using Outlook 2010):

  • exchangeMDB
  • exchangeRFR
  • exchangeAB
  • HTTP

KERBEROS METAPHOR

As mentioned earlier, Kerberos has 3 components, the client, the server, and the KDC (trusted 3rd party). The process is similar to when you travel to a foreign country.

  1. You visit the local passport office with a birth certificate
    (get the Ticket Granting Ticket ticket from the KDC)
  2. You request an entrance Visa for your passport in order to enter the country
    (get the Ticket Granting Service ticket from the KDC – ok, so you would get the Visa from the country’s embassy, but you still need the passport and something authoritative the country’s immigration guard will accept).
  3. You travel to the country with the passport and the country’s entrance Visa
    (present authoritative documentation to gain access to the resource server).

KERBEROS TICKET PROCESS OVERVIEW

Ticket Granting Ticket (aka logon ticket)

1. Joe User logs on with his Active Directory user name and password to a domain-joined computer (usually a workstation). The computer takes the user’s password and runs a one way function (OWF) creating a hash of the password (typically the NTLM hash). Hashing the password is like taking a steak and running it through a meat grinder. The ground beef that is the result can never be reassembled back into the same steak we started with.
This is used to  handle all Kerberos requests for the user (as well as other authentication methods such as NTLM).

2. Kerberos authentication is initiated by sending a timestamp (PREAUTH data) encrypted with the user’s password-based encryption key (password NTLM hash).

3. The user account (JoeUser@adsecurity.org) requests a Kerberos service ticket (TGT) with PREAUTH data (Kerberos Authentication Service Request or AS-REQ).

4. The Domain Controller’s Kerberos service (KDC) receives the authentication request, validates the data, and replies with a TGT (Kerberos AS-REP). The TGT has a Privileged Attribute Certificate (PAC) which contains all the security groups in which the user is a member. The TGT is encrypted and signed by the KDC service account (KRBTGT) and only the domain KRBTGT account can read the data in the TGT.

At this point, the user has a valid TGT which contains the users group membership and is used to prove the user is who they claim to be in further conversations with a Domain Controller (KDC). The TGT is sent to the Domain Controller every time a resource ticket is requested.

Ticket Granting Service ticket (aka resource access ticket)

5. When the user wants to access an AD resource (a file share for example), the user’s TGT from step 4 is presented to a Domain Controller (KDC) as proof of identity with a request for a resource ticket to a specific resource (Service Principal Name). The DC determines if the TGT is valid by checking the TGT’s signature and if valid, generates a resource access ticket (TGS) signed/encrypted with the KRBTGT account and a part encrypted with the Kerberos service account’s session key which the destination service uses to validate the TGS.
Note: The DC doesn’t validate the user has the appropriate access to the service, it only validates the TGT and builds a TGS based on the TGT information.

6. The resource service ticket (TGS) is sent to the user by the Domain Controller and is used for authentication to the resource. At this point, all communication has been between the user’s computer and the Domain Controller (KDC).

7. The user’s computer sends the user’s resource service ticket (TGS) to the service on the resource computer. If the destination service is a file share, the TGS is presented to the CIFS service for access.

8. The destination service (CIFS in this example) validates the TGS by ensuring it can decrypt the TGS component encrypted with the service’s session key. The service may send the TGS to a DC (KDC) to validate the PAC to ensure the user’s group membership presented is accurate. The service reviews the user’s group membership to determine what level of access, if any, the user has to the resource.

THE DETAILED PROCESS

Here’s my example scenario to explain what occurs when a user logs on and opens Outlook to view his Exchange email. The bold text is the simple overview version while the detail follows.

  1. A user logs onto the domain ADSecurity.org on the workstation ADSecurityPC.
  2. The user requests authentication by sending a timestamp encrypted with the users password encryption key.
    The workstation creates an encryption key derived from the user’s password (the user’s password is hashed using a one way function such as MD5 = (A) key) to encrypt a timestamp (date/time) as an authenticator (pre-authentication is required by AD in its default configuration, so the client must send an authenticator) . The authenticator is simply a method the client uses to prove to the KDC that the user is who he claims to be (since only the user & the KDC knows his password) and protects against replay attacks. This information is sent to the KDC in an AS-REQ (Authentication Service Request) packet. This request includes the client supported encryption algorithms.Keys used:
    (A)User’s password derived keyPacket Data:
    User account (user@ADSecurity.org) requests Kerberos service ticket (TGT) with PREAUTH data
    KRB5: Kerberos AS-REQ
    1 Forwardable: FORWARDABLE tickets are allowed/requested
    1 Renewable: This ticket is RENEWABLE
    1 Canonicalize: This is a request for a CANONICALIZED ticket
    1 Renewable OK: We accept RENEWED ticketsClient Name (Principal): admin
    Realm: ADSECURITY.ORG
    Service: krbtgt/ADSecurity.org
    till: 2037-09-12 02:48:05 (UTC)
    rtime: 2037-09-12 02:48:05 (UTC)
    Nonce: 1976014234
    Principal Name: user
    HostAddress: METCORPORGDC02<20>
    PAC_Request: True
    Encryption Types: aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 rc4-hmac rc4-hmac-exp rc4-hmac-old-exp des-cbc-md5KRB5: Kerberos AS-REP
    Client Name (Principal): user
    Tkt-vno: 5
  3. The Kerberos server (KDC) receives the authentication request, validates the data, and replies with a TGT.
    The KDC receives the AS-REQ, decrypts the authenticator (encrypted with key (A)), and validates the timestamp is within the time skew limits set by the domain (5 minutes by default). If the KDC is satisfied the request is a valid user request, the KDC responds with an AS-REP packet which includes the TGT. The TGT can only be decrypted by a KDC (using the (B) key) and is used to authenticate the user to the Kerberos server so it doesn’t have to look up the user’s password (long-term key) again. The KDC also includes a session key ((C)key) for use in future communication with the KC.Keys used:
    (B) Kerberos account’s password derived key
    (C)
    User’s Kerberos service (KDC) session key NOTE: The TGT is encrypted with the KRBTGT account password so only a valid Kerberos server can decrypt it. In an environment with RODCs, each RODC has its own krbtgt account with a unique password. This means that if a user presents a TGT received from a RODC to a writable DC, the DC dumps the TGT and generates a new one.Packet Data:
    The KDC replies with the TGT and session key

    KRB5: Kerberos AS-REP
    Client Name (Principal): User
    Ticket (Tkt-vno): 5
    Realm: ADSECURITY.ORG
    Server Name: krbtgt/ADSecurity.org
    enc-part aes256-cts-hmac-sha1-96
    [Encrypted Key]
    enc-part rc4-hmac
    [Encrypted Key]
  4. The user opens Outlook which locates the user’s mailbox server and requests a TGS ticket for access.
    The workstation locates the Exchange mailbox server containing the user’s mailbox (MetcorpEXMB02.ADSecurity.org) and reads the ServicePrincipalName attribute on the computer account in AD (ExchangeMDB/ADSecurityEXMB02.ADSecurity.org – there are a bunch, so I will just use this one for the example).
    The client then sends a TGS-REQ to the KDC requesting a TGS for access to the Exchange service running on the MetcorpEXMB02 Exchange server. The TGS request includes the target server SPN, the user’s TGT (encrypted with the (B) key), and an authenticator (encrypted with the (C)key).Keys used:
    (B)
    Kerberos account’s password derived key
    (C)
    User’s Kerberos service (KDC) session keyPacket Data:
    User account requests service ticket (TGS) for MetcorpEXMB02 Exchange service access
    KRB5: Kerberos TGS-REQ
    1 Forwardable: FORWARDABLE tickets are allowed/requested
    1 Renewable: This ticket is RENEWABLE
    1 Canonicalize: This is a request for a CANONICALIZED ticket
    Realm: ADSECURITY.ORG
    Server Name: ExchangeMDB/MetcorpEXMB02.ADSecurity.org
    till: 2037-09-12 02:48:05 (UTC)
    Nonce: 1976014234
    Encryption Types: aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 rc4-hmac rc4-hmac-exp rc4-hmac-old-exp des-cbc-md5KRB5: Kerberos AS-REP
  5. The KDC validates the TGS request and replies with the TGS.
    The KDC replies with a TGS-REP packet to the client which includes 2 session tickets (TGS) (2?). One of the session tickets is encrypted with the user’s (KDC) session key ((C) key) and the second one is encrypted with the target server’s (KDC) session key ((D) key). The second TGS also includes the user’s group membership & associated SIDs which provides the server information used to determine authorization and help the server determine: Is the user allowed to access the server’s resource?
    Both session tickets include a new session key ((E)key) for exclusive use in communication between the Exchange server and the user.Keys used:
    (C)
    User’s Kerberos service (KDC) session key
    (D)
    Server’s Kerberos service (KDC) session key
    (E)
    User-Exchange service session keyPacket Data:
    The KDC replies with the service ticket (TGS) for MetcorpEXMB02 Exchange service access
    KRB5: Kerberos TGS-REP
    Client Name (Principal): User
    Ticket (Tkt-vno): 5
    Realm: ADSECURITY.ORG
    Server Name: krbtgt/ADSecurity.org
    enc-part aes256-cts-hmac-sha1-96
    [Encrypted Key]
    enc-part rc4-hmac
    [Encrypted Key]
  6. The client authenticates to the Exchange server with the session ticket.
    The client sends the target server (MetcorpEXMB02.ADSecurity.org) an AP-REQ packet containing the TGS it received from the KDC encrypted with the server’s session key ((D) key) and an authenticator encrypted with the user-Exchange server session key ((E) key) . This lets the Exchange server know that the user was authenticated to the Kerberos domain (realm) and that the TGS is valid (assuming the Exchange server is able to decrypt it). The client also sends the server an authenticator (timestamp) encrypted with the session key ((E)key) it received from the KDC in Step 5. The Exchange server decrypts the TGS, extracts the user’s group information, extracts the session key, and uses the session key to decrypt the authenticator. This provides the server enough information to make an authorization decision. If the user is authorized to connect to the server, it sends a reply.Keys used:
    (C)
    User’s Kerberos service (KDC) session key
    (D)
    Server’s Kerberos service (KDC) session key
    (E)
    User-Exchange service session key
  7. The Exchange server replies that authorization to the service is granted.
    The Exchange server sends the client an AP-REP packet which includes its own authenticator encrypted with the user-Exchange service session key ((E) key). This assumes the client requested mutual authentication which is the default configuration.Keys used:
    (E)
    User-Exchange service session key

Note:
This is a simplified explanation of Kerberos and doesn’t cover everything involved in this process.

Kerberos Key Storage Locatons

Workstation Keys:

  • User Key
  • Ticket-Granting Ticket
  • Ticket-Granting Service Session Key
  • Service Ticket
  • Session Key

Domain Controller:

  • User Key
  • Ticket-Granting Service Key
  • Service Key

Server:

  • Service Key
  • Session Key

TICKETING

There are different “tickets” that are used to authenticate a client to a server’s resource. The client can be a user or a computer.

The Ticket Granting Ticket (TGT) is the first ticket given to the requester (user or computer.

The TGT is comprised of the following fields:

  • Ticket Version Number
  • Realm: The AD domain name in CAPITAL LETTERS
  • Server Name: The KDC
  • Flags: Kerberos Flag options
  • Key
  • Client Realm: The client’s AD domain name in CAPITAL LETTERS
  • Client Name: The user name
  • Transited: If the user is in a different domain than the resource, Kerberos tickets have transited.
  • Authentication
  • Time
  • Start Time
  • End Time
  • Renew Till
  • Client Address
  • Authorization Data

Ticket Flags:

  • FORWARDABLE
  • FORWARDED
  • PROXIABLE
  • PROXY
  • MAY-POSTDATE
  • POSTDATED
  • INVALID
  • RENEWABLE
  • INITIAL
  • PRE-AUTHENT
  • HW-AUTHENT

Supported Encryption Algorithms & Key Lengths:

DEFAULT AD KERBEROS POLICY SETTINGS

  • Enforce user logon restrictions: Enabled
  • Maximum lifetime for service ticket: 600 minutes (10 hours)
  • Maximum lifetime for user ticket: 600 minutes (10 hours)
  • Maximum lifetime for user ticket renewal : 7 days
  • Maximum tolerance for computer clock synchronization: 5 minutes

References:

PowerShell v5 Preview

PowerShell Magazine notes that the September 2014 preview of Windows Management Framework 5.0 (PowerShell v5) is available for download here.

Here’s a list of changes as noted in this article by PowerShell Magazine:

Some of these changes are:

  • Generate Windows PowerShell cmdlets based on an OData endpoint
  • Manage .ZIP files with new cmdlets
  • DSC Authoring Improvements in Windows PowerShell ISE
  • New Attribute for defining DSC meta-configuration
  • Use partial configurations DSC
  • Cross-computer synchronization through DSC
  • Get the current DSC configuration status
  • Compare, Update, and Publish DSC configurations
  • Audit Windows PowerShell usage by transcription and logging
  • Extract and parse structured objects out of string content
  • Extend the item noun to enable Symbolic Links
  • Develop with classes in Windows PowerShell
  • Register a PSRepository with PowerShell Get
  • Network Switch management through Windows PowerShell (improvements)