What is the role of HKLM in the Windows startup process?
During the Windows startup process, the operating system reads values from HKLM to determine the system’s configuration and initialize hardware and software components. It plays a crucial role in ensuring that the system boots up correctly and that the necessary resources are available for applications.
Can I export and import settings from HKLM?
Yes, you can export and import settings from HKLM using the Registry Editor tool. This allows you to back up specific configurations or transfer settings between different computers. It is a useful feature when migrating to a new system or when sharing specific settings with others.
What happens if HKLM gets corrupted?
If HKLM becomes corrupted, it can lead to various issues, including system instability, application crashes, and incorrect behavior. In severe cases, it may prevent the operating system from booting correctly. Regular backups and exercising caution while modifying the registry can help mitigate the risk of corruption.
How can I backup HKLM?
To back up HKLM, you can use the Registry Editor tool. Right-click on the “Computer” or “This personal computer (PC)” icon, select “Export,” choose a location to save the backup file, and give it a name. This creates a copy of the selected keys and values, allowing you to restore them if needed.
Is it safe to delete keys in HKLM?
It is generally not recommended to delete keys in HKLM unless you are certain about their purpose and impact. Deleting essential keys can cause system malfunction, application failures, and other undesirable consequences. It is advised to seek expert guidance or refer to reliable sources before deleting any keys.
HKLM is specific to the Windows operating system and its registry structure. Non-Windows operating systems have their own mechanisms for storing system and application configurations. Therefore, HKLM is not accessible on operating systems like Linux, or Android.
You can access HKLM programmatically using programming languages such as C#, VB.NET, or PowerShell. These languages provide libraries and application programming interfaces (APIs) to interact with the registry. For example, in C#, you can use the Microsoft.Win32.RegistryKey class to open and manipulate keys and values within HKLM.
Can I transfer HKLM settings to another computer?
Yes, you can transfer HKLM settings to another computer using the registry export and import functionality. By exporting specific keys or subkeys from the Registry Editor on one computer and importing them on another, you can replicate settings across different systems. This is useful when configuring multiple computers with the same settings or when migrating to a new machine.
Yes, you can view HKLM settings using the Command Prompt or PowerShell. In Command Prompt, you can use the reg query command, and in PowerShell, you can use the Get-ItemProperty cmdlet to retrieve information from HKLM.
Can I create my own subkeys and values in HKLM?
It is generally recommended to avoid creating your own subkeys and values directly in HKLM unless you have a specific need and understand the potential consequences. Modifying the wrong subkey or value can lead to system instability or software compatibility issues. It’s best to consult expert guidance or use dedicated software installation methods when adding custom configurations.
How can I identify if a software program modifies HKLM during installation?
During software installation, most programs create registry entries under HKLM. You can monitor changes made to HKLM by using registry monitoring tools such as Regshot or Process Monitor. These tools track modifications made to the registry and provided detailed reports of added, modified, or deleted keys and values.
Can I export specific subkeys from HKLM instead of the entire hive?
Yes, you can export specific subkeys from HKLM using the Registry Editor. Simply navigate to the desired subkey, right-click on it, select “Export,” choose a location to save the exported file, and give it a name. This allows you to export and import specific sections of HKLM instead of the entire hive.
Can I modify HKLM settings to improve system performance?
Modifying HKLM settings can impact system performance, but it’s important to exercise caution. Changing certain values without proper knowledge can lead to system instability or even cause the operating system to fail. It is recommended to consult official documentation or seek expert advice before making any modifications.
Are there any specific HKLM keys that should not be modified?
Some HKLM keys should not be modified unless you have a thorough understanding of their purpose and potential consequences. These keys include critical system configuration settings, security-related keys, and keys associated with Windows services. Modifying these keys without proper knowledge can lead to system instability or security vulnerabilities.
Время на прочтение

Основной задачей, которую необходимо решить вредоносному файлу сразу после запуска является закрепление в системе, то есть обеспечение возможно постоянной работы данного процесса в системе. То есть, злоумышленнику необходимо, чтобы процесс, с помощью которого он может получить доступ в систему (троян, бэкдор и т. д.) запускался бы автоматически при загрузке системы и работал во время всего сеанса работы системы. Существует несколько методов закрепиться в системе. В этой статье мы рассмотрим наиболее распространенные способы закрепления в ОС Windows, а также посмотрим, как некоторые из этих техник выглядят в отладчике. Будем считать, что для запуска нужного процесса злоумышленнику так или иначе необходимо запустить выполнимый файл.
Ветка Run
Начнем с наиболее известного места, где можно прописать автоматический запуск приложения при старте системы – реестра Windows. И прежде всего приложения, желающие стартовать вместе с ОС прописывают себя в ветки
Для первого варианта нам необходимы права локального администратора. Для того, чтобы прописать автоматический запуск файла, необходимо добавить новое значение в ветку Run.

Однако, важно понимать, что манипуляции с данными ветками реестра также отслеживают и средства защиты. Так антивирус будет очень внимательно следить за тем, какие приложения собираются прописать свои файлы в эти ветки реестра. И попытка неизвестного ранее приложения прописаться в ветку Run может привести к срабатыванию антивируса.
Также, если вам необходимо один раз выполнить какой-либо файл. Например, вам необходимо прописать в системе сервис, то можно воспользоваться ключом RunOnce.
Если мы хотим выполнить файл один раз для конкретного пользователя, то необходимо прописать файл в ветке:
Однако, этими, наиболее известными ветками реестра возможности спрятаться в автозагрузку не ограничиваются. Так, за автозагрузку в профиле текущего пользователя отвечают ветки реестра показанные ниже.
Посмотрим, как код, правящий реестр выглядит в отладчике.

Конечно, любой здравомыслящий вредонос постарается максимально скрыть от отладки как разделы памяти в которых указаны ветки реестра и записываемые значения, так и сами вызовы функций для работы с реестром. Но в представленном на скриншоте примере мы видим обращения к реестру: RegOpenKeyEx, RegCreateKey, RegCloseKey. По вызовам этих функций можно понять, что приложение в принципе работает с реестром. В случае, если вносятся правки в представленные выше ветки, то вероятнее всего мы имеем дело с вредоносом.
Сервисы в реестре
Еще одним способом поселиться в автозагрузку является использование системных служб – сервисов. Сервис (служба) – это приложение, автоматически исполняемое системой при запуске операционной системы Windows и выполняющиеся вне зависимости от статуса пользователя.
Существует несколько режимов для служб:
Соответственно, для того, чтобы осуществить автоматический запуск какого-либо выполнимого файла, нам необходимо прописать его как сервис. И здесь кроются некоторые сложности. Дело в том, что сервис – это, не совсем обычный выполнимый файл. Для его запуска недостаточно просто создать exe файл и запустить его. Вместо этого нам необходимо зарегистрировать сервис в системе и только потом его можно запускать.
На скриншоте ниже представлен фрагмент кода, в котором формируется набор значений в стеке (в том числе имя выполняемого файла и самого сервиса) и затем все это передается функции CreateService для создания сервиса.

После того, как сервис зарегистрирован в системе его можно запустить с помощью вызова функции OpenService.

Помимо использования функций ОС предназначенных непосредственно для работы с сервисами, для регистрации и запуска сервиса можно воспользоваться командой sc. В примере ниже мы создаем процесс, который запускает команду sc start NewServ. CreateProcess не единственная функция для запуска процессов. В одной из предыдущих статей по реверсингу мы использовали функцию WinExec для запуска калькулятора при реализации переполнения буфера.

В общем, не стоит забывать про такой простой способ работы с сервисами, как консольные команды.
И еще с сервисами можно работать через реестр. Для этого предназначена ветка
В ней находятся разделы, описывающие работу каждого из сервисов, зарегистрированных в операционной системе.

На скриншоте показаны параметры сервиса DHCP. Как видно, в этой ветке имеются параметры, отвечающие за параметры запуска сервиса, аккаунт, от которого он запускается и собственно сам путь к выполнимому файлу. Таким образом, работу с сервисами можно организовать с помощью манипуляций с реестром.
Скрытый отладчик
Представленные выше способы регистрации в автозагрузке в большей или меньшей степени видны пользователю системы. Так запущенные сервисы можно легко увидеть в соответствующей оснастке, а ветки Run хорошо всем известны, и можно без труда проверить их содержимое.
Однако, в реестре есть менее известные ветки, в которые тоже можно подселить выполнимый файл. В данном случае речь пойдет не совсем об автозагрузке как таковой, но при желании здесь тоже можно организовать автозапуск.
Разработчики из Майкрософт очень любят оставлять себе лазейки в виде недокументированных возможностей. В частности, они предусмотрели функционал по автоматическому запуску отладчика для заданного приложения. Работает это следующим образом: в ветке реестра
HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows NTCurrentVersion Image File Execution Options
Мы создаем раздел с именем запускаемого приложения, а в этом разделе создаем параметр Debug в котором уже указываем выполнимый файл, запускаемый в реальности.

То есть, в примере на скриншоте при попытке запуска калькулятора у нас запустится некий prog.exe. Таким образом можно под видом одного приложения запустить другое. Можно к примеру подменить экранную клавиатуру (osk.exe) на командную строку (cmd.exe). В результате можно будет на заблокированном компьютере вызывать клавиатуру и получать командную строку, причем с правами System!
Небезопасные обновления
Продолжая тему реестра и размещения приложений в нем, мы можем поправить команды, которые выполняются при обновлении тех или иных компонентов. В ветке
HKEY_LOCAL_MACHINESOFTWAREMicrosoftActive SetupInstalled Components
Указаны GUID установленных компонентов и для многих из них можно найти параметры StubPath и Version. Далее процитируем официальную документацию Майкрософт:
При входе пользователя система сравнивает содержимое разделов HKLMSoftwareMicrosoftActive SetupInstalled Components и HKCUSoftwareMicrosoftActive SetupInstalled Components. Для каждого раздела в HKLM должна быть копия с тем же GUID в HKCU. Дальше есть три варианта развития событий:
1. Если копии нет, то выполняется команда, указанная в StubPath, после чего в HKCU создается раздел с тем же GUID и прочими параметрами.
2. Если копия есть, то сравнивается значение параметра Version. Если версия в HKCU младше, чем в HKLM, то задание отрабатывает повторно, после чего номер версии в HKCU обновляется.
3. Если же раздел с одинаковым GUID есть и в HKLM и в HKCU и номер версии у них совпадает, то значит компонент уже отработал для данного пользователя и запускать его не требуется.

Таким образом мы можем поиграться со значением StubPath и версиями для того, чтобы в итоге выполнить то, что нам нужно. По сути, здесь тоже можно реализовать автозагрузку.
Переселяем папки
Также с помощью реестра можно “перепрятать” разделы из меню Пуск. В ветке HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindowsCurrentVersionExplorerShell Folders
Размещаются пути к различным компонентам, включая меню Автозагрузка. Соответственно, здесь мы тоже можем поменять значения параметров для того, чтобы запускать файлы из другого каталога.

Планировщик задач
Помимо реестра мы можем попробовать прописать свое приложение в XML файлы с описанием задач. В каталоге %WINDIR%System32Tasks находятся XML файлы в которых прописано выполнение тех или иных действий и расписание, по которому эти действия выполняются.

Помимо прочего, в них можно найти и те команды, которые должны выполняться в рамках этой задачи.

Таким образом мы получаем еще один вектор для закрепления в системе.
Заключение
В этой статье мы рассмотрели основные методы размещения выполнимых файлов в системе для автозагрузки. Знание этих методов может помочь в выявлении подозрительных активностей злоумышленников в системе.
О других инструментах для обеспечения безопасности можно узнать у экспертов в области ИБ, например на онлайн-курсах. Перед стартом обучения проходят открытые уроки от преподавателей курсов, на которых можно узнать об актуальных технологиях и задать интересующие вопросы экспертам.
The Windows Registry is a critical component that lies deep within your system and directly affects its performance. Take action now to better understand this powerful tool and maximise your PC’s performance!
Regedit is a tool for editing the Windows Registry. Using Regedit, you can change system settings, customise application behaviour and even improve the appearance and functionality of Windows.
The regedit window contains five main keys:
Each of these keys is divided into smaller keys and values. Each key represents a set of settings, and each value is a piece of data associated with a setting.
To make a change in Regedit, locate the relevant key and value, and then change the value. To change the value, right-click the value and select Edit.
Taking a Backup in Regedit
Before making any changes to regedit, we recommend that you take a backup. This will allow you to restore the registry in case of a problem.
If you have taken a backup in Regedit, you can restore the registry using this backup.
Regedit can be used in various ways to customise Windows. Here are some common uses:
How to customise system settings via Windows Registry
Here are some things you can do using Regedit to customise system settings:
It is important to be careful when using regedit. Making an incorrect change to the registry can cause Windows to corrupt or even crash.
Before using Regedit, it is recommended that you back up the registry. This will allow you to restore the registry in case of a problem.
Here are some useful registry keys and values that can be used to customise system settings:
These are just a few examples. There are many ways to customise system settings using Regedit.
Security and permissions protection in Windows Registry
Make a Backup: Before making any changes to the Registry, you should always take a backup. This is important so that you can restore your system to its previous state in case of a possible error.
Minimum Permissions: When making changes to Registry keys, you should only have the necessary permissions. For example, if you want to change the settings of a software, you should only modify the Registry keys for that software.
Making Changes Step by Step: If you need to make many changes to the Registry, make these changes step by step and check your system after each step. This will help you identify potential errors and help you determine which change is causing the problem.
Not Changing Unknown Values: You should never change a value in the Registry unless you know what it does. Changing an unknown value can jeopardise your system stability.
Regular Checking and Cleaning: The Registry can become filled with unnecessary entries over time. Cleaning these entries regularly can help your system run faster and more stable. However, you should be careful when doing this cleaning and only take action when you know what you are doing.
The importance of registry backup tools
Taking a backup before any changes to the Registry is critical to prevent potential problems. Here are the importance of Registry backup tools and points to be considered:
Data Security: Making a wrong change in the Registry can make your system inoperable. Backup tools help you create a fallback point to fix possible errors.
Time Saving: Manually backing up the Registry can be a time-consuming process. Backup tools allow you to do this quickly and easily.
Regular Backups: Some backup tools have the ability to perform automatic backups at regular intervals. This helps you to keep the Registry up-to-date.
Selective Backup: When backing up the Registry, there are tools that allow you to select only certain keys and values. This makes the backup process more efficient.
Ease of Restore: In the unlikely event of a problem, backup tools allow you to quickly restore the Registry to its previous state.
Improving System Performance: Regular backup and cleaning optimises the Registry and contributes to more stable and faster system operation.
For example, using a backup tool, you can back up the Registry before performing an important software update. If you encounter a problem after the update, you can use the backup tool to quickly restore the Registry to its previous state and restore your system to normal operation.
Introduction to registry cleaning tools
Over time, the Registry may fill up with old and unnecessary entries. This can negatively affect system performance. This is where Registry cleaning tools come into play. These tools optimise your system by detecting and removing unnecessary entries. However, there are some important points to be considered while doing this process:
Backup: Before any cleaning process is started, it is vital to make a backup of the Registry. In the unlikely event of an error, this backup can be used to restore the Registry to its previous state.
Reliable Tool Usage: There are many Registry cleaning tools available in the market. However, it is important to use only reliable and reputable tools. Misleading or malicious software can cause more damage to your system.
Automatic Cleaning: Some tools offer the possibility to clean all unnecessary entries with a single click. However, you should be careful when using this feature. Some valid entries may be mistakenly marked as unnecessary.
Performance Improvement: When the Registry is cleaned, system resources are used more efficiently, which can lead to an increase in overall system performance.
Regular Use: Regular use of Registry cleaning tools helps to ensure that the system is continually optimised. However, overly frequent use may result in the loss of some important entries.
System Security: Registry cleaning may be mistakenly detected by security software as a malicious action. Therefore, it is important to check security software before performing a cleanup.
Impact of Windows services on the registry
The Registry contains the startup types of Windows services, their operating parameters and other services they depend on. Services have their own keys, which are located under “HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServices”. Under each service’s key are various values and settings that determine how the service behaves.
In addition, the other services and workgroups that services depend on are specified in the Registry through the “DependOnService” and “Group” values. Through these settings, dependencies between services and the order of operation can be organised.
The importance of registry optimisation for system performance
Over time, with an increase in installed and uninstalled programs, the Registry can become bloated and filled with old, unused entries. This can lead to system slowdown, reduced performance and even system errors.
Registry optimisation cleans out these redundancies, allowing the system to run faster and more stable. Optimisation includes cleaning unnecessary entries, fixing broken links and improving the Registry structure. These operations improve overall system performance by enabling the Registry to be scanned faster and system resources to be used more efficiently.
However, care should be taken when optimising the Registry. Because the Registry is a very sensitive structure containing the basic settings of Windows. Care should be taken not to delete critical entries during optimisation operations, and a Registry backup should be taken before the operations. In this way, in case of a possible error, the system can be restored to its previous state.
Here are some sample operations that can be performed within the scope of Registry optimisation:
If you have uninstalled a program from your system, you may still have Registry entries related to that program. It is possible to lighten the Registry by cleaning such old and unused entries. For example, you can manually delete folders related to the uninstalled programme under “HKEY_LOCAL_MACHINESOFTWARE”.
The entries under “HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServices” control Windows services. By modifying this field you can change the startup behaviour of certain services and even disable some services. However, this can be risky and may have negative effects on your system, so you should be very careful.
You can optimise the memory management settings of Windows by editing the values in “HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerMemory Management”. This can improve system performance, especially for older computers with low hardware.
Windows Registry Compatibility with Different Windows Versions
Windows Registry is a component of Microsoft’s operating systems that has evolved over many versions. With each new version of Windows, the Registry structure and functionality has been updated and improved. However, the basic principles and structure have remained largely unchanged, allowing some Registry entries created in older versions to work in newer versions.
When migrating from older versions such as Windows XP and Windows 7 to newer versions such as Windows 8, Windows 10, and Windows 11, Microsoft has made significant efforts to maintain compatibility. This has ensured that older software and settings will still work on newer systems. However, in some cases, older Registry entries may have been handled differently or removed entirely in newer versions.
Windows Registry, when managed effectively, supports the smooth and fast operation of the system. However, careless or incorrectly made changes can lead to system errors and performance problems. Therefore, it is important to adopt best practices for maintaining and organising the Registry.
Backup: It is vital to make a complete backup of the Registry before making any changes. This makes it possible to revert back to the original settings in case of possible errors.
Careful Changes: It is important not to make any changes to the Registry without fully understanding the effects of the changes. Research the relevant registry keys and their values before making changes.
Making Use of Cleaning Tools: There are many reliable Registry cleaning tools available in the market. These tools optimise the system by cleaning unused or invalid entries.
Regular Maintenance: Regularly reviewing and optimising the system improves performance and prevents potential problems.
Avoiding Unnecessary Software: Avoiding installing software from unknown or unreliable sources prevents potential harmful effects to the Registry.
Keeping Up to Date: Keeping the operating system and other software up-to-date prevents unnecessary entries from accumulating in the Registry and keeps the system safe.
Use Application Settings Instead of Manual Editing: Whenever possible, choose to make changes through application settings. This reduces the risk of erroneous manual changes to the Registry.
HKCR is the abbreviation for this Hive. The Information that is stored here makes sure that the correct program opens when you open a file by using Windows Explorer.
HKLM is the abbreviation for this Hive and it contains configuration information and settings that apply to the local computer. SAM and SYSTEM subkeys reside in this Hive and are often prime target for attackers.
HKCC is the abbreviation for this Hive and it contains information about the hardware profile that is used by the local computer at system start-up.
I have provided a very high level look at a very important and in some cases complex topic consisting of the Windows registry. In an effort to simplify what can be a difficult subject to get your head around, I have provided this brief insight into what indicators to be aware of when dealing with the registry in the scope of Cybersecurity. I haven’t mentioned the abundance of tools out there which are used for the analysis of the registry because that is a separate topic in its own right.



