Охота за кредами
Уровень сложностиСредний
Время на прочтение3 мин
Количество просмотров7.5K
Базы данных паролей
Существуют различные способы аутентификации в системах Windows, каждый из этих способов сохраняет или кэширует переданные учетные данные. В этом модуле мы рассмотрим основные типы аутентификации и места кэширования переданных данных, а также разберем, как можно получить к ним доступ.
Данная статья представлена исключительно в образовательных целях. Red Team сообщество «GISCYBERTEAM» не несёт ответственности за любые последствия ее использования третьими лицами.
SAM
Хэши паролей всех локальных учетных записей хранятся в файле реестра SAM (System Account Manager). По своей сути, SAM — это база данных учетных записей, доступ к которой можно получить множеством различных способов. Например, можно сохранить ветки реестра HKLM\SYSTEM и HKLM\SAM, передать на свой хост и с помощью impacket-secretsdump извлечь пароли:
C:> reg save HKLM\SYSTEM SYSTEM
C:> reg save HKLM\SAM SAM
impacket-secretsdump -system SYSTEM -sam SAM
Или можно сразу сдампить пароли удаленно:
impacket-secretsdump DOMAIN/USER:PASSWORD@TARGET_IP
Еще мы можем вытащить пароли с помощью mimikatz, также предварительно сохранив файлы SAM и SYSTEM:
lsadump::sam /system:SYSTEM /sam:SAM
Либо через оболочку meterpreter в metasploit:
meterpreter> hashdump
Внимание! Для получения доступа к файлам SAM и SYSTEM необходимо обладать привилегиями бэкап-оператора, администратора или системы.
LSA и LSASS
LSA (The Local Security Authority) — это защищенная подсистема Windwos, которая хранит сведения обо всех аспектах локальной безопасности.
LSASS (The Local Security Authority Subsystem Service) — это процесс в системах Windows, который отвечает за управление различными механизмами аутентификации. Он выполняет проверку учетных данных как локальных, так и доменных пользователей, а также отвечает за хранение в памяти учетных данных пользователей.
Для дампа LSASS-процесса, как и SAM базы, существует множество инструментов и техник. Наиболее популярные среди них:
-
Mimikatz
-
ProcDump (из состава Windows Sysinternals)
-
pypykatz
Более новые и продвинутые инструменты:
-
MirrorDump
-
NanoDump
-
Physmem2profit
NTDS.DIT
Файл NTDS.DIT представляет собой базу данных, расположенную на контроллере домена в папке C:\Windows\NTDS\. В этой базе данных хранится информация Active Directory о пользователях, группах и членстве в группах. В эту базу данных также входят хэши паролей всех пользователей в домене.
Типы аутентификации
Теперь рассмотрим различные типы входа в системах Windows, посмотрим как генерируются события этого типа входа и рассмотрим как сохраняются учетные данные для них.
Interactive Logon
Интерактивный вход в систему — это вход на физической машине после включения либо же запуск процесса через runas:
runas /user:USER cmd.exe
В данном случае, если вход производится с локальной учетной записью, то NT хэш заносится в SAM. Если же учетная запись доменная — то хэш заносится в lsass, а компьютер дополнительно проверит переданные учетные данные путем запроса TGT билета, который будет сохранен в кэш. Содержимое кэша билетов можно посмотреть с помощью команды:
klist
ID для такого типа входа — 2.
NewCredentials Logon
NewCredentials Logon происходит, когда используется runas с флагом /netonly
:
runas /user:USER cmd.exe /netonly
В этом случае переданные учетные данные будут использоваться только в том случае, когда процессу необходимо будет сетевое подключение, а до тех пор, они не будут проверяться, а процесс будет выполняться в контексте текущего пользователя.
Для этого типа входа используется ID 9.
Эти учетные данные также будут сохранены в процессе lsass.
Network Logon
Этот тип входа осуществляется через сеть при подключении, например, к WinRM, SMB, RPC и т.п. Для аутентификации этого типа мы можем использовать пароль, хэш или Kerberos тикет, а значит при данном варианте мы можем использовать атаки Pass-the-Hash, Pass-the-Ticket или Pass-the-Key.
При network logon’е данные нигде не сохраняются. Такой тип логина логируется с ID 3.
Batch Logon
Batch Logon тип используется при запуске задач по расписанию под каким-либо пользователем. Этот тип логина помечается с ID 4
Учетные данные в таком случае сохраняются в lsass при запуске задачи.
Remote Interactive Logon
Remote Interactive Logon используется когда мы подключаемся к удаленной машине по RDP. Такой тип логона имеет идентификатор 10
RDP использует CredSSP для аутентификации, поэтому пароли отправляются по сети на удаленный хост и кэшируются в процессе lsass.
Протокол CredSSP (Поставщик поддержки безопасности учетных данных) — это поставщик поддержки безопасности, который реализуется с помощью интерфейса поставщика поддержки безопасности (SSPI), позволяющий приложению делегировать учетные данные пользователя от клиента целевому серверу для удаленной проверки подлинности.
Заключение
Сегодня мы с вами разобрали основные типы логонов в Windows и выяснили, в каких ситуациях сохраняются учетные данные. Таким образом получается, что учетные данные сохраняются при Interactive Logon, Remote Interactive Logon, Batch Logon и NewCredentials Logon. В случае Network Logon креды не кэшируются.
Подписывайтесь на наш Telegram-канал
From Wikipedia, the free encyclopedia
The Security Account Manager (SAM) is a database file[1] in Windows NT, Windows 2000, Windows XP, Windows Vista, Windows 7, 8.1, 10 and 11 that stores users’ passwords. It can be used to authenticate local and remote users. Beginning with Windows 2000 SP4, Active Directory authenticates remote users. SAM uses cryptographic measures to prevent unauthenticated users accessing the system.
The user passwords are stored in a hashed format in a registry hive either as an LM hash or as an NTLM hash. This file can be found in %SystemRoot%/system32/config/SAM
and is mounted on HKLM/SAM
and SYSTEM
privileges are required to view it.
In an attempt to improve the security of the SAM database against offline software cracking, Microsoft introduced the SYSKEY function in Windows NT 4.0. When SYSKEY is enabled, the on-disk copy of the SAM file is partially encrypted, so that the password hash values for all local accounts stored in the SAM are encrypted with a key (usually also referred to as the «SYSKEY»). It can be enabled by running the syskey
program.[2] As of Windows 10 version 1709, syskey
was removed due to a combination of insecure security[3] and misuse by bad actors to lock users out of systems.
In 2012, it was demonstrated that every possible 8-character NTLM password hash permutation can be cracked in under 6 hours.[4]
In 2019, this time was reduced to roughly 2.5 hours by using more modern hardware.[5][6]
In the case of online attacks, it is not possible to simply copy the SAM file to another location. The SAM file cannot be moved or copied while Windows is running, since the Windows kernel obtains and keeps an exclusive filesystem lock on the SAM file, and will not release that lock until the operating system has shut down or a «Blue Screen of Death» exception has been thrown. However, the in-memory copy of the contents of the SAM can be dumped using various techniques (including pwdump), making the password hashes available for offline brute-force attack.
LM hash is a compromised protocol and has been replaced by NTLM hash. Most versions of Windows can be configured to disable the creation and storage of valid LM hashes when the user changes their password. Windows Vista and later versions of Windows disable LM hash by default. Note: enabling this setting does not immediately clear the LM hash values from the SAM, but rather enables an additional check during password change operations that will instead store a «dummy» value in the location in the SAM database where the LM hash is otherwise stored. (This dummy value has no relationship to the user’s password — it is the same value used for all user accounts.)
In Windows NT 3.51, NT 4.0 and 2000, an attack was devised to bypass the local authentication system. If the SAM file is deleted from the hard drive (e.g. mounting the Windows OS volume into an alternate operating system), the attacker could log in as any account with no password. This flaw was corrected with Windows XP, which shows an error message and shuts down the computer. However, there exist software utilities,[7] which, by the aforementioned methodology of using either an emulated virtual drive, or boot disk (usually Unix/Linux, or another copy of Windows like Windows Preinstallation Environment) based environment to mount the local drive housing the active NTFS partition, and using programmed software routines and function calls from within assigned memory stacks to isolate the SAM file from the Windows NT system installation directory structure (default: %SystemRoot%/system32/config/SAM
) and, depending on the particular software utility being used, removes the password hashes stored for user accounts in their entirety, or in some cases, modify the user account passwords directly from this environment.
This software has both a highly pragmatic and beneficial use as a password clearing or account recovering utility for individuals who have lost or forgotten their Windows account passwords, as well as a possible use as a malicious software security bypassing utility. Essentially granting a user with enough ability, experience, and familiarity with both the cracking utility software and the security routines of the Windows NT kernel (as well as offline and immediate local access to the target computer) the capability to entirely bypass or remove the Windows account passwords from a potential target computer. Only recently, Microsoft released a utility called LockSmith, which is part of Microsoft Diagnostics and Recovery Toolset (DaRT).[8] DaRT is not freely available to end-users, however.[9]
In July 2021, it was revealed there was a vulnerability within Windows 10 and Windows 11 that allowed low privileged users to access sensitive Registry database files including the SAM file.[10]
- chntpw
- Password file
- ^ «Security Account Manager (SAM)». TechNet. Microsoft. Retrieved 11 April 2014.
- ^
«How to use the SysKey utility to secure the Windows Security Account Manager database». Support. Microsoft Corporation. Retrieved 12 April 2014. - ^ Deland-Han. «Syskey.exe utility is no longer supported — Windows Server». learn.microsoft.com. Retrieved 2023-01-17.
- ^ Goodin, Dan (2012-12-10). «25-GPU cluster cracks every standard Windows password in <6 hours». Ars Technica. Retrieved 2020-11-23.
- ^ Claburn, Thomas (February 14, 2019). «Use an 8-char Windows NTLM password? Don’t. Every single one can be cracked in under 2.5hrs». www.theregister.co.uk. Retrieved 2020-11-26.
- ^ hashcat (2019-02-13). «hand-tuned hashcat 6.0.0 beta and 2080Ti (stock clocks) breaks NTLM cracking speed mark of 100GH/s on a single compute device». @hashcat. Retrieved 2019-02-26.
- ^ An example of offline NT password attack utility: http://cdslow.org.ru/en/ntpwedit/index.html
- ^ «Overview of the Tools in DaRT 10 — Microsoft Desktop Optimization Pack». learn.microsoft.com. Microsoft Corporation. 20 April 2021. Retrieved 15 November 2024.
- ^ «About DaRT 10 — Microsoft Desktop Optimization Pack». learn.microsoft.com. Microsoft Corporation. 20 April 2021. Retrieved 15 November 2024.
- ^ Abrams, Lawrence (2021-07-20). «New Windows 10 vulnerability allows anyone to get admin privileges». Bleeping Computer. Retrieved 2024-11-12.
What is the Security Account Manager (SAM)?
When you log in to your Windows Operating System, you must enter a password to gain access to the system. Have you ever wondered where your passwords are stored when you set up any new user account, create a new password, or update your existing passwords? All the passwords of the Windows operating system are stored in a Security Account Manager (SAM) file in the SAM database.
What is SAM?
Windows stores and manages the local user and group accounts in a database file called Security Account Manager (SAM). It authenticates local user logons. On a Domain Controller, simply stores the administrator account from the time it was a server, which serves as the Directory Services Restore Mode (DSRM) recovery account. The SAM database resides in the Windows registry. It is available on Windows XP, Vista, 7, 8.1, 10, and 11.
What is the purpose of SAM?
The SAM database runs automatically as a background process when the computer starts up. The SAM also works together with other processes and services that run It is known that Windows computers can be configured to be in a workgroup or joined to a domain. In a workgroup, each computer has its own SAM which contains information about all its local users and group accounts. The passwords associated with each of these accounts are hashed and stored in the SAM. The hashing of passwords offers some security measures and minimizes an attack’s risks. The Local Security Authority (LSA) validates a user’s logon attempt by verifying their credentials against the data stored in the SAM. A user’s logon attempt is successful only when the entered password matches the password stored in the local SAM.
In a domain-joined computer, there can be two types of logons: a local logon (that is handled by the SAM as described above) and a domain user logon using the Active Directory (AD) database with the WinLogon service. However, when a user logs on to a computer as a local user, the user will not be able to access the network resources. A Windows server that has been promoted to a DC will use the AD database instead of the SAM to store data. The only instance it will use the SAM would be to boot into DSRM for performing maintenance operations. This is because the DSRM administrator password is stored locally in the SAM and not in AD.
Simply put, be it a domain-joined computer or a standalone computer, local logon can occur only through the SAM.
How does SAM work?
The SAM database runs automatically as a background process when the computer starts up. The SAM also works together with other processes and services that run on the computer, by providing the security information needed. The primary goal of the SAM is to increase system security and protect against data breaches if the system credentials are stolen.
Where to find the Security Account Manager file?
Go to This PC -> C drive.
Inside the C drive, open Windows -> System32 -> config.
The hashed values of all passwords find a place in the HKEY_LOCAL_MACHINE\SAM of the registry. However, there are rules that govern ‘when’ and ‘who’ can access this file.
Even though it is stored locally, any user cannot access the file while it is running. Continue reading to find out why the SAM failure message appears, what happens when you delete a SAM file, and how to restore it.
Causes of SAM initialization failure:
The following can be the reasons for the causes of SAM initialization failure:
- In some cases, a Security Accounts Manager (SAM) file is corrupted or missing. If a file is missing, Windows cannot locate it and terminates its current tasks.
- Windows cannot read a corrupted file correctly. In addition, if a file is missing or corrupt, the boot process is halted. Instead of continuing, the process terminates and an error message is displayed. The error message is as follows:
Security Accounts Manager initialization failed because of the following error: A device attached to the system is not functioning. Error Status: 0xc0000001. Please click OK to shut down this system and reboot into Safe Mode, check the event log for more detailed information.
Key boot-related system files are corrupted due to disc write errors, power outages, or virus attacks.
How to extract a SAM file using Command Prompt (CMD)?
Using CMD is the simplest method to extract a SAM file, because all the other methods require you to download external tools, or use shadow volumes.
- Run Command Prompt as system administrator.
- Run the following to extract a SAM file from a SAM database
reg save hklm\sam c:\sam
(where c:\sam indicates the name and drive of the output file.)
- Run the following to extract the system key
reg save hklm\system c:\system
(where c:\system indicates the name and drive of the output file.)
- After successful execution, you will find a SAM file and system key in the location mentioned in the command.
Note: The output files are encrypted, and you can dump the hashes to get the password.
Is it possible to disable SAM?
Disabling SAM will cause services and programs on your computer to stop working properly. SAM also grants access to services such as the Internet and email, as well as other processes like requiring administrator-level user accounts. Other services and processes will fail to start if SAM is disabled, and they will not be notified when SAM is ready to deliver security information to running services and processes.
What happens after deleting a SAM file?
A SAM file is responsible for storing the local users’ passwords on a workgroup computer. Normally, while Windows is running, it is impossible to delete a SAM file, as it is locked to all users by the Windows Kernel.
If a SAM is somehow deleted in some way while Windows is running, the system loses all user account passwords, resulting in Windows throwing an error exception “Security Accounts Manager initialization failed because of the following error: A device attached to the system is not functioning. Error Status: 0xc0000001. Please click OK to shutdown this system and reboot into Safe Mode, check event log for more detailed information” and shutting down.
If a SAM is deleted while Windows is not running, for example when booting from a live Linux media, Windows is unable to load the user login screen and will crash. A backup copy of a SAM may be found in the folder C:\Windows\System32\config\RegBack, but you have no control or knowledge of when it was backed up.
How to restore the Security Account Manager?
You can restore the database file if SAM is missing from your office computer or if you receive a notification claiming that SAM is corrupt.
- Search for lsass.exe in the i386 directory on your C: drive.
- Copy the file’s name by right-clicking it and selecting Copy.
- Open the System32 directory in the Windows folder on your machine.
- Right-click anywhere in the directory pane and select Paste.
- To finish the database installation, restart your computer.
System administrators must familiarize themselves with SAM and how it works to understand, how Windows processes and stores credentials. This in turn will help administrators devise safer password management and security practices- monitor and resolve issues such as SAM failure or authentication delays, ensuring that the user experience is uncompromised. Despite receiving multiple criticisms for security flaws, SAM can still help defend the system from most attacks when used in combination with recommended practices such as providing limited access and permissions to users and enforcing password and account lockout policies.
User authentication and user authorization process: An explanation
NTLM authentication and Kerberos Authentication Protocols Explained
What is a workgroup and how is it set up?
DNS and Active Directory
What is the Security Accounts Manager (SAM)?
The Security Accounts Manager (SAM) is a database file in the Microsoft Windows operating system (OS) that contains usernames and passwords.
The primary purpose of the SAM is to make the system more secure and protect from a data breach in case the system is stolen. The SAM is available in different versions of Windows, including Windows XP, Windows Vista, Windows 7, Windows 8.1, Windows 10 and the Windows 11.
What does the Security Accounts Manager do?
Each user account can be assigned a local area network (LAN) password and a Microsoft Windows password in the SAM. For increasing security, both of these are encrypted and cannot be accessed by any user. These are also referred to as password hashes. In simple terms, think of it as a locked diary with all a user’s passwords.
During a user’s login attempt, the Windows system will ask for a username and password. Once the password is entered, it will be verified against the password in the SAM. If the username and associated passwords match an entry in the SAM, a sequence of events will take place. This will ultimately result in granting the user access to the system.
On the other hand, if the username and passwords do not match any entry in the SAM, it will return an error message. The user will be requested to enter the information again.
If the personal computer (PC) is used by only one user, and the PC is not connected to LAN, the SAM will only store and ask for one user’s password. Once the system is accessed, the SAM file continues to run in the background.
What is the purpose of the Security Accounts Manager?
The primary purpose of the SAM in a PC environment is to make it difficult for a thief to access the data on a stolen machine. It can also provide some measure of security against online hackers.
If the user does not care for such security, they can disable this function to access the system without inputting the password. In such a case, the user will not be asked to enter authentication data every time the computer is switched on or restarted.
Can a user access the Security Accounts Manager?
SAM is part of the registry and can be found in the C Drive on the hard disk. This means that the SAM data is locally stored.
Due to this, it is used in the case of a local logon. The user will only be able to access the data which is stored in that profile. However, domain user logon attempts are handled by the Active Directory (AD). Similarly, a Windows server with a domain controller (DC) will also access login data from the AD.
The SAM database file is stored within C:\Windows\System32\config. All of the data within the file is encrypted. The passwords hashes are stored in HKEY_LOCAL_MACHINE\SAM. As the primary purpose of the SAM is to increase security, its access is restricted.
Even though it is stored locally, any system user cannot access the file while running. For security reasons, different permissions govern access to the SAM. HKLM/SAM and SYSTEM privileges are required for accessing it. For added security, Windows introduced the Syskey function in Windows NT 4.0. This can be activated using the Syskey program.
See also: Construct a solid Active Directory password policy, Incorporating zero trust into endpoint security, A closer look at new and updated Microsoft security features and How to enable and disable Tamper Protection in Windows 10.
This was last updated in February 2022
Continue Reading About Security Accounts Manager
- Get a grasp on using group managed service accounts
- Security Think Tank: Consider cyber policies and procedures as you welcome employees back
- What you need to know about the Windows Security Accounts Manager
- Comparing macOS vs. Windows security
- 7 mobile device security best practices for businesses
Dig Deeper on Windows 10 security and management
-
rainbow table
By: Alexander Gillis
-
Top 5 Windows 10 monitoring tools for business
By: Robert Sheldon
-
restore point
By: Gavin Wright
-
Auto-enrolment begins for Google multi-factor authentication
By: Alex Scroxton