Active Directory AutoRecovery from Dirty Shutdown

The Problem

I found couple of events in a Windows 2012 Domain Controller that indicates a problem in the DFS replication. The event looks like this :

AD AutoRecovery 

It turned out that Microsoft had published a hotfix  http://support.microsoft.com/kb/2663685 that will disable the ability to AutoRecovery after dirty shutdown. I am sure that the domain admin will not always updated if one of his domain controllers suffered a power failure, which will cause DFS to be broken and SYSVOL to stop replication. 

The bad news, is that Microsoft made this the default behavior for Windows 2012 !

How to solve this

Find out what drive holds your DFS folders, if it is the C drive, then type the following to know what is the volume ID :

Mountvol C:   /L

Then :

wmic /namespace:\\root\microsoftdfs path dfsrVolumeConfig where volumeGuid=”{Volume-ID}” call ResumeReplication   

(do not include the “{” and “}” when replacing the volume-id

Finally, run :

wmic /namespace:\\root\microsoftdfs path dfsrmachineconfig set StopReplicationOnAutoRecovery=FALSE


			

Shaking BitLocker – Backup keys to AD and play around

I have come across many scenarios where people have their BitLocker Information in AD, and then different funny situation happened along the way that i want to talk about in this blog post.

Problems

Case 1 : What will happen if you rejoin a BitLocker protected computer to the domain

Case 2 : Renaming a computer which has BitLocker

Case 3 : Computer was used by user1, user1 resigned, so you reset his computer account in AD, reformatted the machine, join it to domain and re-enabled BitLocker on it

Case 4 : deleting computer which has BitLocker from AD

Case 5 : Enabling BitLocker before joining the machine to the domain

Case 6 : divergence happened, you have a domain joined machine with BitLocker enabled, and in AD you do not have recovery information for that computer.

Moving to a New Blog Platform

This post is now moved to my new blog platform at https://blog.ahasayen.com. To continue reading this blog post, please click here

https://blog.ahasayen.com/bitlocker-tips-and-tricks/

AD Backup – PowerShell Script

Mission :

I do not want to use third party software to backup my Active Directory (Domain Controller’s system state) because usually those third party requires high privileges and rights on domain controllers.

Instead, i will have a protected file share server, i will use a script on the domain controller to backup its system state to that protected file share. Then i will use my favorite third party solution to backup the protected file share server.

AD_script_Backup_@32

Prepare the File Server

Now as the file share will host your AD backup, it is important to protect and restrict access on that file server. I would recommend to install a VM with C drive for the O.S and D drive to host the system state backup.

Also, make sure that the administrators group on that file share is restricted to only domain admins. Do not install any other server roles on the server and do not host any other shares on it.

Now on the D drive, create a hidden share with Full permissions given to (Domain Controllers) group on both sharing and NTFS permissions. (Domain Controllers) is a built in security group that exist on your AD by default.

Prepare the Domain Controller

Nothing to prepare really here. You need to schedule the below script on one of your domain controllers. That’s it.

Script Breakdown

The script should be scheduled to run on any domain controller and it should run using the built in (System) scrutiny context. This will give it the right to take backups to your AD without any additional rights 🙂

The script starts by importing the (Server Manager) module using the Import-Module ServerManager

Then we will get the current date [string]$date = get-date -f ‘yyyy-MM-dd’.

Following that we will define the folder on the remote file share $TargetUNC = “\\FileServer\ADBackup$\AD-$date”. 

This assumes that the remote file share name is (FileServer) and the hidden share we created is called ADBackups$

Notice that we are assuming that backups will be taken in a folder structure where the name of the folder contains the date on which the backup is taken.

So we will check first to see if a folder is already there that contains today’s date, and if it exists, we will delete it. This means that we will not maintain two backups taken in the same date. This is only my own way. You can do yours.

Because the script will try to create folders on the remote share, (Domain Controllers) group will need access on that remote file share

If ( Test-Path $TargetUNC) { Remove-Item -Path $TargetUNC -Recurse -Force }

New-Item -ItemType Directory -Force -Path $TargetUNC

Finally, we will start taking backup using WEBADMIN command. This command requires that in order to do backups to remote file share, a user name and password should be supplied. So create a username (i.e ServiceADBackup) and give it share and NTFS permissions to write to the remote file share.

$WBadmin_cmd =    “wbadmin.exe START BACKUP     -backupTarget:$TargetUNC   -systemState      -noverify     -vssCopy     -quiet     -user:MyUser     -password:MyPassword “

Invoke-Expression   $WBadmin_cmd

Schedule Script

In order to schedule the script on your DC, open Task scheduler , create basic task with your own schedule preference, and when you reach the Action window, make sure to put (C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe) on the Program/script field, and the full path of your script in the (Add arguments (optional)) filed.

AD_Backup_2322

When you are done, open the task again, and change the scrutiny context that the script is using, and replace it with (System) and check the (Run with highest privileges)

AD_Backup_23322

Download Script

You can download the script from here http://sdrv.ms/1aMzCfd

Final Note

When taking backups this way, logs for this backup are stored on that DC here (C:\Windows\Logs\WindowsServerBackup). Usually with time, those logs will consume big space, so i would run a script to delete log files from this directory using another script https://ammarhasayen.com/2013/10/23/delete-log-files-older-than-x-days/

monitor active directory backup

The Requirement

“Send me email if my AD was not backed up recently”

I was given a task for making sure that AD backups (system state) is working fine and to get alerts if it fails.

If you go to the internet, you will find many solutions for taking backup for the domain controller’s system state. If you are using Windows Built in Backup Software, then you can write a script to search for specific event IDs under the Backup Event Log category. This was my initial thought. You will find many scripts out there who look at that place. But those scripts will only work if you are using Windows Backup Built in software.

I wanted a more direct, more reliable, more abstracted way to check AD backups. I want to go to AD and ask it : When the last time you get backed up, and then get alerts if this exceeded my backup cycle Window.

How to solve it ?

Lucky me, i found this nice article talking about PowerShell and AD stuff. It is a smart way to get the backup status for each AD partition, and the script is written in a way that works in all environments and no hard coding is used.

They use those line of code to get the last backup stamp for each AD partition

Import-Module ActiveDirectory

[string]$dnsRoot = (Get-ADDomain).DNSRoot

[string[]]$Partitions = (Get-ADRootDSE).namingContexts
$contextType = [System.DirectoryServices.ActiveDirectory.DirectoryContextType]::Domain
$context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext($contextType,$dnsRoot)
$domainController = [System.DirectoryServices.ActiveDirectory.DomainController]::findOne($context)

ForEach($partition in $partitions)
{
$domainControllerMetadata = $domainController.GetReplicationMetadata($partition)
$dsaSignature = $domainControllerMetadata.Item(“dsaSignature”)
Write-Host “$partition was backed up $($dsaSignature.LastOriginatingChangeTime.DateTime)`n”
}

What we need to do is to use the same line of codes but instead of printing out the last backup stamp for each partition, we will configure the script to send us a nice email if the last backup stamp for any partition exceeded our backup window for AD. For example, if we are suppose to take AD backup everyday using our favorite backup solution, then an email will be sent if the last backup stamp on any AD partition is more than 1 day.

Download the script

My own and complete version of the script can be download  from here http://sdrv.ms/19HgVvV

The script does not need any special permissions. Any domain user can execute it. The script will take from you your AD backup frequency and will send email alert for you ONLY if the AD backup exceeded your backup frequency (i.e you have AD backup failure).

 

 

The script can be sc

Test your Active Directory Backups on an isolated VM

It is without any doubts, one of the most critical tasks that Active Directory administrators forget/ignore !

It is not enough to take backups of your Active Directory (which can be done simply by backing up the domain controller’s System State) , as you also need to verify that the backup can be restored.

Note: Backing up the domain controller’s system state will backup your whole Active Directory, SYSVOL (Your Group Policies) and your[ DNS zones (only if they are integrated in Active Directory).]

Scenario : What is the test scenario 

Suppose you have couple of domain controllers at your enterprise. You are taking AD backups in regular basis which you should always do (by taking backup to DC’s system state).

You are asked to verify that the Active Directory backup that you are taking is healthy and can be restored. You may have also been asked to perform regular restores as part of a certain regulations or procedures.

So you want to create a virtual machine, restore the Active Directory backup on it, and have a look to your Active Directory Users and Computers snap in to verify your AD objects are restored, and may be verify all your GPOs are restored. Then you can destroy this VM and you are done.

Let us do it

1.  Create a virtual machine

  • Virtual Machine name : DOES NOT MATTER
  • Virtual Machine network connectivity : it should have a disabled network card at this stage. Never Ever allow this machine to access or route to your live environment in any way.
  • Virtual machine domain membership : Not joined to any domain (should be a workgroup)
  • It is recommended to have an additional disk on this VM to host the restored files

2.  Now go to one of your domain controller and let us start creating a backup job:

  • We need to take backup for the domain controller’s system state.
  • We will be using the Windows Built in Server Backup software and we are assuming that the domain controller is running Windows 2008 and above
  • To use it, you need to go to Add Features, and add (Windows Server Backup) component manually.
  • Now open the Windows Server Backup console.

ADRestore__2211

  • Click on (Backup Once) to start the backup job.
  • In the (Backup Options), click (Different Options)

a1

  • In the (Select Backup Configuration), select (Custom)

a2

  • In the (Select Items for Backup) click (Add Items) and click the (System State)

a3

  • In the (Specify Destination Type), click what fits you

a4

  • That’s it. Just wait for the backup to finish, and you will see a folder named (WindowsImageBackup).
  • You can also go to the DC Event Log, under Microsoft>Backup>Operational and find the event ID = 4 that indicates successful backup operation.

3.  Now, go to you VM, i assume that it has C and D drive, and do the following :

  • In a secure and isolated way, move the WindowsImageBackup folder as is , to the root of the D drive D drive of the VM. This should happen without connecting the VM to the network at all.

Note: ALWAYS located the WindowsImageBackup to the root of the data drive of the VM. This will allow the Backup software to locate it easily

4.  As the restored files are now located under (BackupDC) folder on the VM D drive, and after ensuring that the VM is isolated and not connected to any network and cannot route traffic to your live environment, perform the following to start the restore:

  • Boot the VM on the (Advanced Boot Options) ,most cases by clicking F8 during boot, and click (Directory Services Restore Mode).

Notice that this VM doesn’t have any active directory on it, but still you will this option available .

ADRestore__5211

  • Now the VM will boot in the (Directory Services Mode)

ADRestore__1211

  • Now from this mode, open the Windows Server Backup console on the VM (install it from the Add Features if it is not installed yet).
  • Click on the (recovery) option to start the recovery wizard.
  • on the (Getting Started) page, click (A backup stored on another location)ADRestore__3211
  • On the (Specify Location Type) click (Local drives).

ADRestore__4211

  • In the (Select Backup Date), leave defaults

ADRestore__7211

  • On the (Select Recovery Type) click (System State)

ADRestore__8211

  • On the (Select Location for System State Recovery) leave the defaults (which is Original Location)

ADRestore__9211

  • You will get an confirmation box, click OK and continue

ADRestore__10211

  • Acknowledge the Confirmation box

ADRestore__11211

ADRestore__12211

5.  Now after the recovery process is completed, you can go to the VM > C:\Windows\NTDS and confirm that the AD databases are there, and you can go to the SYSVOL directory and confirm that your group policies are there

6. This is the tricky part !! If you try to open the Active Directory Users and Computers or even GPMC.msc console from the VM , you will get an error that the domain does not exist. This is absolutely normal. The reason is that the restored DC in the VM needs to point to itself as a DNS server. So what you should do is to enable the network card on the VM and giving it fake IP and subnet mask, and configure the DNS on its network card to point to itself (to its fake IP). MAKE SURE THAT STILL THE VM CANNOT ROUTE TRAFFIC TO YOUR LIVE ENVIRONMENT.

Now, wait a little bit or restart the VM and then try to browse the Active Directory Users and Computers, and it will work. You can now see all your AD objects. If you open GPMC.MSC , you can see all your group policies.

Note: If you didn’t find the Active Directory Users and Computer console on the VM after the restore, go to run>mmc.msc and add the Active Directory Users and Computers snap-in manually

7. After you have confirmed everything looks fine, destroy the VM and never connect it to your network. Have a nice restore day !!!

 

Notes:

  • First of all you cannot take backup from a version of Windows and restore to another version. The Windows Backup will give you catalog corrupted error. For example, if you are taking a backup from Windows 2012 DC, you can it restore it using Windows Backup on a Windows 2008 R2 server
  • After you finish all the restore, and when you will notice that the DNS may not show you any data because it was Active Directory to do some initial synchronization. On the other hand, the AD cannot start without a DNS. To solve this issue, on the VM add this registry

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NTDS\Parameters]

“Repl Perform Initial Synchronizations”=dword:00000000

You Bit !! Active Directory AD Computer Statistics Script Report (With Charts)

We are all used to csv file formats, HTML tables and other form of presenting information when scripting using powershell. This is very nice if you want to get deep analysis.

But wouldn’t it be better if you can have chart graphical representation ? I bit you do.

This script when you download it and run it, will go to your AD, get computer objects, break them down to servers and workstations, and will give you full overview of the O.S versions in your Avtive Directory

Download the Script

You can download the script from here Get-ADComputerVersionReport.ps1

Script Charts 

When you run the script, you will get a nice HTML table that contains overall statistics of all computers in your AD and a breakdown per O.S

The email that you will receive contains a chart for workstation OS breakdown, and a chart for server OS breakdown.

PowerShell Computer  OS Report

PowerShell Computer Server OS Report

Script Filtering

You can search the script code for a line that starts with ( -SearchBase “DC=Contoso,DC=Com) and un comment it by deleting the (#), and then enter any LDAP Path to scope the script to a certain LDAP path.

For example, you can use SearchBase = “OU= …., OU=…., DC=contoso,DC=com”

Script Output

1.   Email that contains

    • HTML Table with full statistics
    • Two charts : one for servers and one for Workstations

2.  CSV file with extensive information , generated in the script working directory

Tell me what do you think.

BitLocker Killer Mistake

Assumptions

You have BitLocker deployment where you backup your BitLocker recovery key to Active Directory.

The wrong thing

When you format a computer, you go to AD, delete the computer account, and create a new one, then you join the formatted machine to domain! Killer mistake indeed!!!

The right thing

When you format a computer, you go to AD, (RESET THE COMPUTER ACCOUNT) , and then join the formatted machine to machine!

 What can go wrong if I delete computer account

When you enable BitLocker on a computer drive, the machine will write BitLocker Recovery information on the computer account in AD. So if you delete a computer account, you will delete all BitLocker recovery information. Instead resetting computer account will not.

Common Mistake Scenario

A computer with C and D drive with BitLocker enabled on both of them. You backed up everything in the C drive and since the C drive is big enough, you decided to keep the D and only format the C drive.

You start installing Windows 8 for example on the C drive, you deleted the computer account from AD, and then you created a new one. Then you join the machine to domain, and enable BitLocker on the C drive.

Now you noticed the D drive is encrypted. You went to AD to find a recovery information for that drive. BOOOOM!!! no recovery information since you deleted the computer account and created a new one. Good luck with that.

Remember to always reset computer accounts instead of the old habit of deleting them

BitLocker PowerShell Script Backup Encrypted Keys (How and Why)

BitLocker is a great out of the box encryption tool for disk volumes. If you read about this technology, you realize that the most challenging part is the disk recovery key and how to maintain/backup it.

Well, Microsoft did a great job documenting different ways for doing that. One of those methods is to backup keys to Active Directory. Simple and easy, even you can control this behavior via Group Policies.

Problem

Let me describe the problem with BitLocker AD Key Backup and Recovery

Now, Imagine that you enabled BitLocker key recovery in Active Directory. This will simply create an entry per volume on a specific multi value attribute in the computer object.

Image

Now, suppose that you have deleted the computer object from AD.

Or think about this scenario : The computer has C drive with O.S and D drive for data, both are bitlocker encrypted. You decided to format the C drive and join it again to the domain, so you format the C drive, delete the computer object AD, so you could join it to the domain again. Now think about the recovery key for the D drive in this scenario !!!!! It is lost when you deleted the computer object.

Bad things happen and believe me that you will always find your self in a situation where computer objects get deleted, even as part of organized cleanup process.

You will end up, getting back to AD restore or AD recycle bin, and believe they are not that easy to deal with.

Solution !!!

I have created a simple script that needs only read access to Computer objects and to BitLocker Recovery Information.

(Read this blog for information about how to delegate permissions to read BitLocker Information)

Now here is the script that will go to all computer objects in your Active Directory, and create a nice CSV file for you with all recovery keys for all BitLocker Computers. You can schedule it to run daily and you can keep those CSV for a month and then automatically delete the oldest.

This way, you will have a solid place to go to when some one deleted a computer object and you need the BitLocker Recovery Key. Believe me , this helped me a lot.

Note : The machine from which the script will run, should have Quest Active Directory PowerShell command. You can download it from here  http://www.quest.com/powershell/activeroles-server.aspx

Script Output

CSV File with Object Name, Computer Name, and other attributes. The most ipmortant one is the (Recovery Password) field. This is the one that you can use to unlock BitLocker volume.

AD BitLocker Key Recovery

Download the script 

You can download the script from here Get-ADBitLockerInfo

Examples

.EXAMPLE

 Collect information from the whole directory and save the output CSV file to C:\Scripts

.\Get-ADBitLockerInfo.ps1 $filepath C:\scripts

.EXAMPLE

 Collect information from the whole directory and save the output CSV file current directory

.\Get-ADBitLockerInfo.ps1 $filepath .\

.EXAMPLE

 Collect information from computers under a certain AD Organizational Unit (OU), and save the output CSV file to C:\Scripts

.\Get-ADBitLockerInfo.ps1 $filepath C:\scripts -OrganizationalUnit “OU=LON,DC=CONTOSO,DC=COM”

Active Directory AD Inactive Computer Cleanup Script

On of the most wanted scripts in every organization.

You definitely need a way to identify inactive computers in your network (active Directory) and get a detailed report, and perhaps act on this manually or automatically.

First Question : How to identify Inactive Computers ?

the answer is simply mentioned in one of my blog posts. For simplicity, you can identify inactive computer by looking at the Computer last Password reset attribute (pwdLastSet).

Each computer has a password in AD and each computer will attempt to change this password automatically every X days (by default once every 30 days). This behavior can be controlled by group policy under (Computer Configuration> Windows Setting > Security Settings> Security Options > ” Domain Member: Maximum machine account password age”).

So if every computer will (by default) contact domain controllers and change their password once every 30 days, then computers who didn’t change their password in 60 days for example, are considered for sure inactive. (60 Days is a very safe threshold, usually 45 days is a good practice)

ComputerPassword

Second Question : What to do with inactive computers?

Usually you don’t want to delete them, or maybe you want. I prefer created a separate a quarantined OU named (Inactive Computers)  , and then disable each inactive computer and move it to this OU.

Third Point/Question : What is the preferred frequency for doing cleanup.

It depends. I usually do it once every quarter.

Forth Point: Be careful

I have discovered that sometimes, some computer accounts like Cluster Computer objects or so , do not reset their passwords with AD. May be this was the case with legacy systems, but keep an eye on this.

I prefer that you do not invoke actions automatically on data center servers, instead, get a report on what is seemed to be inactive server and act manually on them after communicating with other teams.

The Script :

you can get the script from here :

DOWNLOAD LINK  : http://sdrv.ms/1eMAbfV

AD Inactive Computers 23232

Script Description 

Here we go…. now focus with me for five minutes.

Preparation :

You need to first make sure that the computer that is running the script has the (Active Directory Power Shell) module.  You need also to download Quest Active Directory PowerShell Extensions on that machine and run their MSI. It is a free AD PowerShell extension and the best in the market. (http://www.quest.com/powershell/activeroles-server.aspx)

This is for example how to install the Active Directory PowerShell module on Windows 7 machine (http://blogs.msdn.com/b/rkramesh/archive/2012/01/17/how-to-add-active-directory-module-in-powershell-in-windows-7.aspx)

For Quest Active Directory PowerShell extensions, the link i mentioned above contains the place to download the free quest PowerShell MSI extension.Just run the MSI and you are ready to go.

So why do we need those modules to be installed on the machine from which the script should run ? Well, we need Active Directory PowerShell module as we need to query Active Directory. We also need Quest Active Directory PowerShell extensions because they have very extended commands that makes it easy to query inactive directory.

Finally, you need to run the script with an account that has permission to read AD Computer objects, and the write to disable computer accounts and the write to move computer accounts to the quarantined OU.

Script Modes :

  1.  Report Mode : In this mode, the script will run and will identify inactive computers.It will also send you a nice email with the total number of inactive computers and a breakdown per OU. No actions will be performed
  2. Action Mode : In this mode, the script will Disable and Move inactive computers to a quarantined OU that you will specify in the first lines of the script + the script will send a nice report for inactive computers

You can control which mode the script will run, by modifying the script , by simply setting the    [bool]$ReportOnly  = $True .  

$True will trigger the script to work in report mode, while $false value will trigger it to work in Action Mode

Customize the script for your environment

[int]$DaysforPasswordSet     = 60   : this line of code means that the script will consider computers which dint reset their password with Active directory for more than 60 days , as inactive computers

[string]$ExcludedComputersG      = “Excluded Inactive Computers”  : If you create a security group in your active directory named (Excluded Inactive Computers), and you populate it with computer accounts, then the script will query this group and will not perform any action on those computers. Think of this as a bypass list of computers. I am using a normal security group to group those computers.

$QuarantineOU = “contoso.com/inactive computers” : this is the OU in which inactive computers will be moved to , if the script is running in the (action Mode)

$SearchBase_Sites    = “contoso.com/sites” : This is the root directory that the script will search in. In your case, you can set to to wider scope, like “contoso.com” or a narrow scope like “contoso.com/OU1/OU2”

Finally, the last line of the script will send an email with the result. By default, the script will set the email sender to (noreply@contoso.com), the recipient to (admin@contoso.com), the smtp server to (smtp.contoso.com). Ofcourse you need to customize those settings.

Final Thought

Imagine that someone came to you and ask you to enable a certain computer and move it back to its original OU.  Since the script will disable and move inactive computers to a quarantined OU in Action Mode, then how can you remember the original location of the computer before it was disabled and moved ?

The script will solve this for you. When the script moves a computer to the quarantined OU, it will write the original OU path of the computer on the computer’s custom attribute 1. So just open an attribute editor or adsi.edit, and browse to the computer’s custom attribute 1 , and you will find there the original location of the computer before it was moved.

Last Advise :

Run the script in Report mode once and twice until you are very sure that you fully understand the script power and logic. Also, prevent running the script in Action Mode to data center computers. Instead, run it in reporting mode, and send the results to your Data center admin.

 

DC Locator

 

I was wondering how clients discover their domain controller and what will happen if the DC located near the client is down?

First of all , its all about DNS .. Your machine will boot ,contact DNS asking about couple of Service Records asking about all domain controllers in the domain. At this time , the client doesn’t know even in which AD Site it is located nor does the DNS.

DNS will return all domain controllers to the client ,and by default it will sort the list using subnet mask ordering feature , that is preferring DCs that share the same network ID with the client. This is a DNS feature and it is enabled by default.

The client will contact each DC in the list until it can connect to a one. The DC then validate the client IP and will return back to him his assigned AD Site name. This information will be cached in the client memory.

The client then will go to DNS and asking for domain controllers located in  THAT AD site.

Now…if the local domain controller is down, the client will go and try to contact ANY domain controller in the domain. This is bad.

How can we make the client contact a domain controller in the nearest AD site if his local DC is down ?

In the figure below ,suppose that the DC at site C is down, clients in site C will try to randomly pick domain controllers at site A or site B although Site A is the near site.

image

There is a GPO settings called ( Try next closest site) , when DC at site C is down, clients will prefer domain controllers at site A.If it cannot connect to a domain controller in the nearest site, it will randomly pick any domain controller in the domain.

Ref: http://technet.microsoft.com/en-us/library/cc733142(WS.10).aspx

 

Last note :

By design , clients will not contact domain controllers in the nearest site if it contains RODCs because it may be considered less secure.This is called (Next Closest Site Filter).

you can modify the filter used by the DC Locator. On Windows Server 2008 DCs, open the registry editor and navigate to HKLM\System\CurrentControlSet\Services\Netlogon\Parameters. Set the NextClosestSiteFilter DWORD value to one of the following:

  • 0: No filtering and any site is used.
  • 1: Sites that only contain RODCs are filtered but sites that contain a mix of RODCs and writable DCs aren’t filtered.
  • 2 (default): Sites that contain any RODCs are filtered.

Kerberos in AD 101

Although Kerberos might seem like black magic to many system administrators,it is the main authentication protocol in Active Directory environment.It is used every time we log to our domain joined machines as well as when access resources such as shares and applications.

Kerberos is an authentication protocol and it doesn’t perform any kind of authorization. Instead, Kerberos will provide the infrastructure (some thing called PAC) so that kerborized applications and services can decide by themselves whether the user is authorized and maybe creating a token for him.

I will start by naming an AD domain controller as KDC (Key Destruction Center) and defining two services running on each DC :

 

image

  • Authentication Service (AS) : used to authenticate users.
  • Ticket Granting Service (TGS) : used to enable users to gain access to resources.

Kerberos and the three parties :

The Kerberos protocol name is based on the three- headed dog figure from Greek mythology known as Kerberos. The three heads of Kerberos comprise :

  • Key Distribution Center (KDC)
  • The client user
  • The server with the desired service to access

image

It is important to notice that  AS and TGS are separated which means that a user can obtain a TGT from one KDC and present it to the TGS on another KDC (maybe on another trusted domain).

Authentication Service (AS) Deep Drive:

Step 1 : Request to get TGT  (AS_REQ)

When you sit down at your workstation and press Ctrl+Alt+Del to log on and enter your credentials, your machine begins the process of authentication.

image

The request will include plain text data that includes :

  • Client Name : user UPN or legacy SAMAccountName
  • Service Name : which is the (krbtgt) service of  the user’s domain.

 

This is the Kerberos RFC standard for AS_REQ . It is plain text of data including the user name and the Kerberos service . It is a claim sent as plain text.

This request is subject to replay attach, so Microsoft added another field, which is called (Kerberos Pre Authentication) . This is simply the client Time encrypted with the user password hash. If the encrypted timestamp isn’t within five minutes of the current time, the request is rejected

You can disable Kerberos Pre-Authentication for any user by unchecking the corresponding checkbox on his user property page in AD :

image

Step 2 : Getting the TGT  (AS_REP)

When the KDC receives the AS_REQ, it will do the following :

  • Tries to decrypt the timestamp using a copy of the user password hash.
  • If this operation fails, then an error is returned to the client and the request doesn’t proceed any further.
  • If the decryption is successful and the timestamp is within acceptable limits, the KDC returns an AS_REP (Authentication Service Reply)

 

Note : if the user didn’t send the encrypted timestamp as part of the AS_REQ (if the Kerberos pre-authentication is disabled) ,the KDC will also return back the same AS_REP. The catch here is only the legitimate user can decrypt and understand the content of the AS_REP.

The AS_REP contains the following :

 

  • Encrypted with user password hash :
  • Session key :  will be used to encrypt future communication with the KDC.
  • Lifetime : to indicate when the user need to renew its TGT.
  • the actual TGT > Encrypted by the KDC Secret :
  • Session key : same one that is mentioned above.
  • Token information or PAC
  • Lifetime: so the KDC can know when this TGT is expired

 

At this point, the user’s machine caches the TGT and session key for the lifetime of the TGT and disposes of the user’s password. By default, TGTs issued by AD KDCs expire after ten hours.

Definitions :

KDC Secret :

When the first domain controller in a domain is created, a user named krbtgt is created with a random password. All writable DCs in that domain share the password of that user and they use it to encrypt the content of TGT. That means that a TGT issued by one domain controller can be decrypted and used on another domain controller to get a service ticket.

It is also important to notice that RODCs have their own krbtgt passwords and they don’t have knowledge of the domain krbtgt password. On the other hand, writable domain controllers have read access to the krbtgt of all RODCs.

PAC :

Part of the TGT is the user token information or PAC. PAC is Privilege Attribute Certificate and it is also considered the (Authorization Data). It contains user groups membership and other user rights and info ( like logon scripts path, home folder directory,etc).

 Ticket Granting Service (TSS) Deep Drive:

Step 1 : Request Service Ticket  (TGS_REQ)

To access a service, you need to present a service ticket to the service. The first step is to identify the service principal name (SPN) of the service you want to access. Your machine or the application involved (e.g., Internet Explorer) is responsible for forming the SPN.

image

TGS_REQ contains the following info :

  • Service Principal Name .
  • The same TGT encrypted with the KDC Secret.
  • Client name (username) and timestamp encrypted with the session key the client received as part of the AS_REP earlier.This information is again used to prevent replay attacks whereby an attacker reuses a request message.

Step 2 : Get Ticket  (TGS_REP)

When the KDC receives a TGS_REQ message, if a single entry for the SPN is specified, the timestamp is within range, and the TGT is valid (and unexpired), the client will receive a service ticket as part of a TGS_REP message.

image

TGS Reply contains the following information :

    1. Encrypted with the same session key exchanged on the AS_REP :
      1. Service SPN
      2. Time stamp
      3. Service Session Key ( symmetric key to be used between the user and the service)
    2. Encrypted with the Service Password Hash :
      1. Client Name (username)
      2. SPN
      3. Service Session Key
      4. Time Stamp.

Service tickets have a maximum lifetime (which is ten hours by default in AD’s implementation of Kerberos) for which they can be reused.

 Accessing Services :

After the client has a service ticket, the application accessing the service can present that ticket to the service and request access. The mechanics of presenting the service ticket aren’t nearly as standardized as for obtaining the ticket because every application is different. In the case of an HTTP service, the service ticket is embedded in the headers of the HTTP request.

The service ticket is presented to the application in the form of a Kerberos AP_REQ message. The service decrypts the service ticket and obtains the session key, which it can use to decrypt the timestamp and client name fields, which are in turn used to validate the authenticity of the service ticket itself. It’s important to note that even if the service accepts the service ticket, at this point the client has merely authenticated to the service. The task of authorization is still up to the service, based on the information it has about the client.

image

The service ticket typically also includes data known as the Privilege Attribute Certificate, or PAC.  the PAC is called Token Information.This is the same token information the KDC included in the user’s TGT. The PAC is composed of information such as the user’s SID, group membership information, and user security rights/privileges. When a user presents a TGT to the KDC to request a service ticket, the KDC copies the token information from the TGT and includes it in the service ticket’s PAC field. This is the information that the service uses to construct an access token for the user and to verify the user’s authorization, typically based on group membership.

An additional Kerberos message known as an AP_REP or Application Reply is permissible after the user presents a service ticket in the AP_REQ . The Application Reply message is optional; in general, the application won’t send such a message unless an error occurs. One example of when an AP_REP message would be generated is in the case of a client that requests (in the AP_REQ message) that a service prove its identity through a process known as mutual authentication.

How can services like DC map a smart card certificate to an AD account ?

In a big network with multiple domains and a complex forest topology , the most unique identifier for a user is the UPN . So , Microsoft requires smart card logon certificates to include the UPN in the SAN extension of the certificate .

Starting from windows Vista , smart card logon certificates does not need to include the UPN on its extension and this make it more challenging to map a certificate to a user account .

Well , SSL/TLS  services like a portal , can map certificates that do not have SAN , and the mapping is done by using (Issuer Name) and ( Subject Name) .This type of mapping is supported by KDC among other methods .

So how KDC maps certificates to accounts ? (the first method that locates an account successfully wins, and the search stops)

  • If UPN is specified in the SAN extension > then the account is located since UPN is unique per forest.
  • If the username is provided along with the certificate , the username is used for lockup and this is the fastest way as it is string search. Username can be provided by enabling a GPO settings that allows Hints to be displayed in the logon screen that allows the user to enter his username and or his domain .
  • When no domain information is available via the Hints , then the current domain is search by default .If any other domains is to be used for lookup , then a domain hint should be provided .
  • Then tests are performed by (Subject and Issuer Field in the certificate)
  • Then subjectDN ,Serial Number, Subject Key Identifier and Certificate Hash are used in order .Then the SAN attribute is used as last method .

clip_image001

It is important to note that after a mapping is performed  between a certificate and a user name in most mapping methods, the NT_AUTH policy tests should be completed before Kerberos logon is allowed ( The test criteria is found here http://msdn.microsoft.com/en-us/library/aa377163.aspx ).One of the important checks is that the issuer of the user certificate should be a CA registered in the NTAuth Store in the AD configuration Partition under services , public key services.

Note : PKINIT : stands for  Public Key Cryptography for Initial Authentication in Kerberos , and it means using smart cards for logon.

More about Smart Card logon and Certificates Mapping

 

As UPN is the only unique attribute for the user in the forest , then when playing with more than one to one mapping between accounts and certificates , don’t include the UPN in the certificate.

Smart Card logon for multiple certificates into a single account :

A group of users might log on to a single account (for example, an administrator account). For that account, user certificates are mapped so that they are enabled for logon.

Several distinct certificates can also be mapped to a single account (for this to work properly, the certificate cannot have UPNs). 

This is done by Active Directory User and Computer Name Mapping . Right click the single account , choose Name Mappings and import the certificates.

Smart Card logon for a single certificate into multiple accounts :

A single user certificate can be mapped to multiple accounts. For example, a user might be able to log on to his user account and also to log on as a domain administrator. The mapping happens according to the criteria mentioned in my previous blog about smart card certificate mapping.

– You should enable the GPO x509 Hints  to provide the user information for whom you will want to logon as

-There should no UPN present in the certificate.