Any way to see an Active Directory password?
Before you jump to conclusions, let me explain. We have a password reset tool that is not working. For some reason when you use it, it resets your password to some unknown value (Not what you changed it to, or what it was before). I have setup a test «user» in the appropriate OU, and I want to be able to see what the reset tool is changing the password to. That way maybe I can maybe understand what’s going on. Any help would be greatly appreciated.
3 Answers 3
AD passwords (just like Windows ones) are stored using non-reversible encryption, so the standard answer is a definite «NO«.
There is a GPO settings that will tell AD (or any Windows system) to store passwords using reversible encryption, but there is no built-in tool to decrypt them (although there is some documentation floating around on how to do that). Of course, this is exactly as insecure as it looks.
![]()
If you need to see the plain text of what it’s setting it to, and you can’t get the reset tool to spit that info out itself, then you have two options: enabling reversible encryption, or using a password filter.
With reversible encryption, you can get at the original password, but it’s not a pleasant process.
With a password filter, you can dump out all password changes to text, but that’s obviously not a good thing for security when it comes to your non-test users.
If you only need to see the hash to see if it was set correctly, though, then you can dump the hash database and compare.
Getting the password of a user from active directory
Is it possible to get the password of an account on the active directory a machine is joined to? I know this may sound like a dangerous thing to do, but I’d like to launch a process with the user ctx of an admin user, without hard-coding a password.
I’m using .NET 3.5.
![]()
![]()
2 Answers 2
@SLaks you are moderator I know but here, this is not the correct answer.
In Active-directory exists a policy that can be used to made passowrd reversible.
In Windows Server 2008 R2, it exists something called «Fine Grained Password Policy» that allow to change password policy for a given group of users. In FGPP you’ll find msDS-PasswordReversibleEncryptionEnabled attribute.
Be careful @dotnetdev, I DO NOT ADVICE you to use this, but it exists. So It’s not «fundamentally impossible».
My advice is to discover which privileges (system rights) you need for your work and to create a special group for that. Then you create a special user and join it to this new group. After you can store the password of this user (NEVER the admin one) crypted with the admin entity or a service entity.
Get-ADUser: получение информации о пользователях Active Directory из PowerShell
13.10.2022
itpro
Active Directory, PowerShell, Windows Server 2019
комментария 193
Get-ADUser позволяет получить информацию о пользователе Active Directory, его атрибутах и выполнять поиск среди пользователей домена. Это один из наиболее популярных командлетов PowerShell для получения информации из AD. С помощью командлета Get-ADUser можно получить значение любого атрибута учетной записи пользователя AD, вывести список пользователей в домене с нужными атрибутами, экспортировать отчеты по пользователям в CSV файлы, и использовать различные критерии для выборки доменных пользователей.
Командлет Get-ADUser в модуле PowerShell Active Directory
Комадлет Get-ADUser входит в специальный модуль для работы с Active Directory — Active Directory Module for Windows PowerShell. Командлеты модуля RSAT-AD-PowerShell позволяют выполнять различные операции с объектами каталога AD.
В этом примере мы покажем, как с помощью командлета PowerShell Get-ADUser получить информацию о времени последней смены пароля пользователя, когда истекает срок действия пароля и другие данные пользователей.
Для использования модуля RSAT-AD-PowerShell нужно запустить консоль PowerShell с правами администратора и импортировать модуль командой:
В Windows Server 2012 и выше модуль RSAT-AD-PowerShell устанавливается по-умолчанию при развертывании на сервере роли Active Directory Domain Services (AD DS). Для установки модуля на рядовом Windows Server в домен, выполните команду:
Install-WindowsFeature -Name «RSAT-AD-PowerShell» –IncludeAllSubFeature

В десктопных версия Windows 10 и 11 для работы коммандера Get-AdUser нужно установить соответствующую версию RSAT. Установить RSAT можно через Settings -> Apps -> Optional Features -> Add a feature -> RSAT: Active Directory Domain Services and Lightweight Directory Services Tools.

Также вы можете установить модуль AD с помощью PowerShell:
Add-WindowsCapability –online –Name “Rsat.ActiveDirectory.DS-LDS.Tools
Если на компьютере не установлен модуль RSAT-AD-PowerShell, то при запуске команды Get-ADUser появится ошибка:
Проверьте, что модуль установлен, и если нужно, импортируйте его в свою сессию PowerShell:

Import-Module «C:\PS\ADPoSh\Microsoft.ActiveDirectory.Management.dll»
Import-Module «C:\PS\ADPoSh\Microsoft.ActiveDirectory.Management.resources.dll»
Полный список всех аргументов командлета Get-ADUser можно получить так:
Get-ADUser: поиск пользователя AD и вывод атрибутов
Чтобы вывести список всех учетных записей домена, выполните команду:

Чтобы вывести свойства только определенного пользователя, используется параметр –Identity. В качестве Identity можно указать имя пользователя, имя входа (SAMAccountName), DN (Distinguished Name), SID или GUID.
Следующие команды вернут одинаковый результат об одном и том же пользователе:
Get-ADUser –Identity a.ivanov
Get-ADUser –Identity «CN=Andrey A. Ivanov,OU=Users,OU=SPB,OU=RU,DC=winitpro,DC=loc»
Get-ADUser –Identity «Andrey A. Ivanov»

По-умолчанию командлет Get-ADUser возвращает только 10 основных атрибутов (из более чем 120 свойств учетных записей пользователей): DistinguishedName, SamAccountName, Name, SID, UserPrincipalName, ObjectClass, статус аккаунта (Enabled: True/False согласно атрибуту UserAccountControl), и т.д.
В выводе командлета отсутствует информация о времени последней смены пароля пользователя.
Get-ADUSer –Server DC01.winitpro.loc –Identity tstuser
Если нужно получить данные из другого домена, нужно указать имя сервера и учетные данные для доступа к нему:
$cred = Get-Credential
Get-ADUSer tstuser -Server DC01.newdomain.ru -Credential $Cred
Чтобы вывести полную информации обо всех доступных атрибутах пользователя tuser, выполните команду:
Get-ADUser -identity tuser -Properties *

Командлет Get-ADUser с параметром Properties * вывел список всех атрибутов пользователя AD и их значения (включая пустые). Аналогичный список атрибутов пользователей доступен в графической консоли Active Directory Users and Computers ( dsa.msc ) на вкладке редактора атрибутов.
В командлете Get-ADUser можно список атрибутов пользователя, которые нужно выводить. Например, вы хотите вывести значения следующих атрибутов:
- PasswordExpired
- PasswordLastSet
- PasswordNeverExpires
Get-ADUser tuser -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires, lastlogontimestamp

Теперь в информации о пользователе есть данные о статусе аккаунта (Expired: True/False), дате смены пароля и времени последнего входа в домен (lastlogontimestamp). Представим информацию в более удобном табличном виде и уберем все лишние атрибуты с помощью Select-Object –Property или Format-Table:
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires

Получение пользователей из нескольких OU с помощью Get-ADUser
Чтобы вывести пользователей только из определенного контейнера домена (Organizational Unit), воспользуйтесь параметром SearchBase:
Get-ADUser -SearchBase ‘OU=Moscow,DC=winitpro,DC=loc’ -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires
Если вам нужно выбрать пользователей сразу из нескольких OU, используйте следующую конструкцию:
$OUs = «OU=Moscow,DC=winitpro,DC=local»,»OU=SPB,DC=winitpro,DC=loc»
$OUs | foreach
Получить Email адреса пользователей из AD
Email пользователя это один из атрибутов в Active Directory. Чтобы вывести список email адресов пользователей, вы должны добавить поле EmailAddress в атрибуты, отображаемые командлетом Get-ADUser.
Get-ADUser -filter * -properties EmailAddress -SearchBase ‘OU=MSK,DC=winitpro,DC=loc’| select-object Name, EmailAddress

Вывести список активных пользователей с почтовыми адресами:
Get-ADUser -Filter <(mail -ne "null") -and (Enabled -eq "true")>-Properties Surname,GivenName,mail | Select-Object Name,Surname,GivenName,mail | Format-Table
Список пользователей, у которые не задан email адрес:
Get-ADUser -Filter * -Properties EmailAddress | where -Property EmailAddress -eq $null
Следующий пример позволяет выгрузить адресную книгу email адресов компании в виде csv файла, который в дальнейшем можно импортировать в Outlook или Mozilla Thunderbird:
Get-ADUser -Filter <(mail -ne "null") -and (Enabled -eq "true")>-Properties Surname,GivenName,mail | Select-Object Name,Surname,GivenName,mail | Export-Csv -NoTypeInformation -Encoding utf8 -delimiter «,» $env:temp\mail_list.csv
Get-ADUser: экспорт списка пользователей в текстовый или CSV/Excel файл
Полученный список пользователей домена с атрибутами можно выгрузить в текстовый файл:
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires > C:\temp\users.txt
Или вы можете выгрузить пользователей AD в файл CSV, который в дальнейшем будет удобно экспортировать в Excel.
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | select Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires | Export-csv -path c:\temp\user-password-expires-2019.csv -Append -Encoding UTF8
Get-ADUser –Filter: Поиск и фильтрация списка пользователей AD
С помощью параметра –Filter вы можете фильтровать список пользователей по одному или нескольким атрибутам. Это удобно использовать для поиска пользователей в AD, чьи атрибуты соответствуют указанным критериям. В качестве аргументов этого параметра можно указать значения определённых атрибутов пользователей Active Directory. При использовании параметра –Filter командлет Get-ADUser выведет только пользователей, которые соответствуют критериям фильтра.
Например, выведем список активных (Enabled) учётных записей пользователей, чье имя содержит «Dmitry». В примере ниже используется множественный фильтр, вы можете комбинировать условия с помощью стандартных логических операторов сравнения PowerShell. В данном примере атрибуты пользователей должны удовлетворять обоим условиям фильтра (-and):
Get-AdUser -Filter «(Name -like ‘*Dmitry*’) -and (Enabled -eq ‘True’)» -Properties * |select name,enabled

Можно использовать все логические операторы PowerShell для выбора значений атрибутов пользователей ( -eq , -ne , -gt , -ge , -lt , -le , -like , -notlike , -and , -or , и т.д.)
Дополнительно с помощью Sort-Object вы можете отсортировать полученный список пользователей по определенному атрибуту. Кроме того, для выборки пользователей можно использовать командлет Where-Object. Здесь также можно использовать сразу несколько критериев фильтрации.
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires -SearchBase ‘OU=Moscow,DC=winitpro,DC=loc’| where <$_.name –like “*Dmitry*” -and $_.Enabled -eq $true>| sort-object PasswordLastSet | select-object Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires

Таким образом, можно получить список пользователей с любыми необходимыми атрибутами Active Directory.
Для поиска пользователей сразу по нескольким атрибутам (legacyExchangeDN, proxyAddresses, SAMAccountName, Surname, DisplayName, SamAccountName, physicalDeliveryOfficeName, RDN и msExchMailNickname) можно использовать функцию Ambiguous Name Resolution ( ANR ):
Get-ADUser -Filter
Вы можете использовать LDAP фильтр в запросах Get-ADUser. LDAP фильтр указывается с помощью атрибута –LdapFilter.
Get-ADUser -LDAPFilter ‘(&(department=it)(title=devops))’
Часто используемые примеры команд с Get-ADUser для получения информации о пользователях AD
Далее приведем еще несколько полезных вариантов PowerShell запросов о пользователях Active Directory с помощью различных фильтров. Вы можете комбинировать их для получения необходимого списка пользователей домена:
Вывод пользователей AD, имя которых начинается с Roman:
Чтобы подсчитать общее количество всех аккаунтов в Active Directory:
Список всех активных (не заблокированных) учетных записей в AD:
Get-ADUser -Filter
get-aduser -Filter * -Properties Name, WhenCreated | Select name, whenCreated
Вывести всех пользователей, которые были созданы за последние 24 часа (пример отсюда):
$lastday = ((Get-Date).AddDays(-1))
Get-ADUser -filter
Список учетных записей с истекшим сроком действия пароля (срок действия пароля настраивается в доменной политике паролей):
Get-ADUser -filter
Задача: для списка учетных записей, которые хранятся в текстовом файле (по одной учетной записи в строке), нужно получить телефон пользователя из AD и выгрузить информацию в текстовый csv файл (для дальнейшего формирования отчета в Exсel).
Import-Csv c:\ps\usernsme_list.csv | ForEach <
Get-ADUser -identity $_.user -Properties Name, telephoneNumber |
Select Name, telephoneNumber |
Export-CSV c:\ps\export_ad_list.csv -Append -Encoding UTF8
>
Пользователи, которые не меняли свой пароль в течении последних 90 дней:
$90_Days = (Get-Date).adddays(-90)
Get-ADUser -filter
Найти неактивные учетные записи пользователей (не входили в домен более 180 дней). Для получения информации об истории входов пользователей в домен используется атрибут lastLogonTimpestamp:
$user = Get-ADUser winadmin -Properties thumbnailPhoto
$user.thumbnailPhoto | Set-Content winadmin.jpg -Encoding byte
Список групп, в которых состоит учетная запись пользователя:
Get-AdUser winadmin -Properties memberof | Select memberof -expandproperty memberof
Вывести список пользователей из OU, которые состоят в определенной группе безопасности:
Get-ADUser -SearchBase ‘OU=Moscow,DC=winitpro,DC=loc’ -Filter * -properties memberof | Where-Object
Вывести всех пользователей из OU, кроме членов определенной группы:
$Users = Get-ADUser -filter * -SearchBase ‘OU=Moscow,DC=winitpro,DC=loc’ -properties memberOf
ForEach ($User In $Users)
<
$Groups = -join @($User.memberOf)
If ($Groups -notlike ‘*Domain Admins*’)
<
$User.Name
>
>
Экспортировать пользователей из AD со указанием имени OU в графическую таблицу Out-GridView:

Проверить, что пользователь AD существует:
Вывести список компьютеров домена, на которые разрешено входить пользователю (ограничение через атрибут LogonWorkstations):
Get-ADUser AIvanov -Properties LogonWorkstations | Format-List Name, LogonWorkstations
Как узнать пароль пользователя в active directory
Question
Some customers would like to know how the user password is stored in Active Directory and how to view and modify it.
Answer
The users’ password hash is stored in the Active Directory on a user object in the unicodePwd attribute. Instead of storing your user account password in clear-text, Windows generates and stores user account passwords by using two different password representations, generally known as "hashes." When you set or change the password for a user account to a password that contains fewer than 15 characters, Windows generates both a LAN Manager hash (LM hash) and a Windows NT hash (NT hash) of the password. These hashes are stored in the local Security Accounts Manager (SAM) database or in Active Directory.
This unicodePwd attribute can be written under restricted conditions, but it cannot be read due to security reasons. The attribute can only be modified; it cannot be added on object creation or queried by a search. In order to modify this attribute, the client must have a 128-bit Secure Socket Layer (SSL) connection to the server. For this connection to be possible, the server must possess a server certificate for a 128-bit RSA connection, the client must trust the certificate authority (CA) that generated the server certificate, and both client and server must be capable of 128-bit encryption.
More Information
How To Change a Windows 2000 User’s Password Through LDAP
How to set a user’s password with Ldifde
Should you worry about password cracking?
How to prevent Windows from storing a LAN manager hash of your password in Active Directory and local SAM databases
Applies to
Windows Server 2003/R2, Windows Server 2008/R2
All replies
For those who like to dig deeper, here is a complete list of password hashes stored in ntds.dit files:
- MD4 (aka NT Hash) — Used for NTLM authentication.
- LM Hash — Disabled by default since Windows Server 2003 (for a very good reason). Used for LM authentication.
- DES_CBC_MD5 — Salted with user logon name and hashed 4096 times using MD5. Used for Kerberos authentication.
- AES256_CTS_HMAC_SHA1_96, AES128_CTS_HMAC_SHA1_96 — Used for Kerberos authentication since Windows Server 2008. Salted with user logon name and hashed 4096 times using HMAC-SHA1.
- 29 MD5 hashes, each using a different combination of login and domain name. Used for WDigest authentication
- Reversibly encrypted cleartext password — Disabled by default. Required by MS-CHAPv1 RADIUS authentication.
Could you please tell us the new password encryption system of Windows 10 after its anniversary update?
T hanks for posting the above explanation Michael,
That is the clearest explanation of this topic I have seen and I live the DSInternal module 🙂
The above, makes sense to me. and this is what I see when I look inside the database so it all makes send to me
However, when I look at other sites that talks about RC4 like the following link for example
I think of RC4 as a stream encryption protocol and not a hashing protocol? as also noted here https://en.wikipedia.org/wiki/RC4
I know can use a stream cypher as a block cypher (by dividing up streams of bytes into pre-defined block sizes) but normally better to use a cypher designed as a block cypher in the first place (I believe)
Therefore, when people say the uses password is stored in AD using RC4 is occurs to me this is incorrect or was the RC4 cypher used as a block cypher in earlier versions of windows and would therefore be used in place in your Kerberos example below, or am I miss-understanding something?
· MD4 (aka NT Hash) — Used for NTLM authentication.
· LM Hash — Disabled by default since Windows Server 2003 (for a very good reason). Used for LM authentication.
· DES_CBC_MD5 — Salted with user logon name and hashed 4096 times using MD5. Used for Kerberos authentication.
· AES256_CTS_HMAC_SHA1_96, AES128_CTS_HMAC_SHA1_96 — Used for Kerberos authentication since Windows Server 2008. Salted with user logon name and hashed 4096 times using HMAC-SHA1.
· 29 MD5 hashes, each using a different combination of login and domain name. Used for WDigest authentication
· Reversibly encrypted cleartext password — Disabled by default. Required by MS-CHAPv1 RADIUS authentication.
When it comes to MD4 is this use to store the NTLMv2 hash is above it just mentions to NTLM has (e.g. could mean v1 protocol).
Can you please help me with the above to clarify my understanding please?
Also, on related note (to further help me understand) AES is a block cypher using a ‘symmetric key’, also HMAC (hash based message authentication code), need a ‘key’ (sympatric key). So both AES and HMAC require a ‘symmetric’ key to encrypt (and therefore decrypt) the data. Is this key simply derived from the SHA1 hash of the user’s password?